stream-chat 10.1.0 → 10.1.1
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/dist/cjs/index.browser.js +283 -77
- package/dist/cjs/index.browser.js.map +3 -3
- package/dist/cjs/index.node.js +283 -77
- package/dist/cjs/index.node.js.map +3 -3
- package/dist/esm/index.mjs +283 -77
- package/dist/esm/index.mjs.map +3 -3
- package/dist/types/LiveLocationManager.d.ts +22 -0
- package/dist/types/logger.d.ts +1 -1
- package/dist/types/pagination/paginators/BasePaginator.d.ts +62 -11
- package/dist/types/pagination/paginators/ChannelPaginator.d.ts +37 -0
- package/package.json +1 -1
- package/src/LiveLocationManager.ts +69 -17
- package/src/logger.ts +1 -0
- package/src/pagination/paginators/BasePaginator.ts +167 -49
- package/src/pagination/paginators/ChannelPaginator.ts +106 -12
- package/src/pagination/paginators/MessageIntervalPaginator.ts +6 -0
- package/src/pagination/paginators/MessagePaginator.ts +3 -0
|
@@ -17,8 +17,11 @@ export type ScheduledLiveLocationSharing = SharedLiveLocationResponse & {
|
|
|
17
17
|
stopSharingTimeout: ReturnType<typeof setTimeout> | null;
|
|
18
18
|
};
|
|
19
19
|
export type LiveLocationManagerState = {
|
|
20
|
+
/** Whether the user's active live locations have been loaded from the server. */
|
|
20
21
|
ready: boolean;
|
|
21
22
|
messages: Map<MessageId, ScheduledLiveLocationSharing>;
|
|
23
|
+
/** Error of the last failed load of the active live locations. Cleared by a successful load. */
|
|
24
|
+
lastQueryError?: Error;
|
|
22
25
|
};
|
|
23
26
|
export type LiveLocationManagerConstructorParameters = {
|
|
24
27
|
client: StreamChat;
|
|
@@ -41,6 +44,14 @@ export declare class LiveLocationManager extends WithSubscriptions {
|
|
|
41
44
|
private getDeviceId;
|
|
42
45
|
private _deviceId;
|
|
43
46
|
private watchLocation;
|
|
47
|
+
/** The in-flight load of the active live locations, shared by concurrent callers. */
|
|
48
|
+
private stateInitPromise?;
|
|
49
|
+
/**
|
|
50
|
+
* Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
|
|
51
|
+
* `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
|
|
52
|
+
* for these ids are skipped instead of being tracked again.
|
|
53
|
+
*/
|
|
54
|
+
private unregisteredDuringLoad;
|
|
44
55
|
private readonly configController;
|
|
45
56
|
private unsubscribeConfiguration?;
|
|
46
57
|
get configState(): StateStore<LiveLocationManagerConfig>;
|
|
@@ -61,6 +72,15 @@ export declare class LiveLocationManager extends WithSubscriptions {
|
|
|
61
72
|
* @param config - The declarative slice. Leave it out to rebuild from the defaults.
|
|
62
73
|
*/
|
|
63
74
|
initializeConfig(config?: Partial<LiveLocationManagerConfig>): void;
|
|
75
|
+
/**
|
|
76
|
+
* Registers the event subscriptions, then loads the user's active live locations. Registration
|
|
77
|
+
* runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
|
|
78
|
+
* whether or not the load has finished.
|
|
79
|
+
*
|
|
80
|
+
* Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
|
|
81
|
+
* registered, so shares started later are still tracked. The next `init()`, position update or
|
|
82
|
+
* `connection.recovered` event retries the load.
|
|
83
|
+
*/
|
|
64
84
|
init(): Promise<void>;
|
|
65
85
|
registerSubscriptions: () => void;
|
|
66
86
|
/**
|
|
@@ -77,7 +97,9 @@ export declare class LiveLocationManager extends WithSubscriptions {
|
|
|
77
97
|
get messages(): Map<string, ScheduledLiveLocationSharing>;
|
|
78
98
|
get stateIsReady(): boolean;
|
|
79
99
|
get deviceId(): string;
|
|
100
|
+
/** Loads the active live locations unless already loaded. Never rejects. */
|
|
80
101
|
private assureStateInit;
|
|
102
|
+
private loadState;
|
|
81
103
|
private subscribeTargetMessagesChange;
|
|
82
104
|
private subscribeWatchLocation;
|
|
83
105
|
private subscribeLiveLocationSharingUpdates;
|
package/dist/types/logger.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as scopedLogger from '@stream-io/logger';
|
|
2
|
-
export type ChatLoggerScope = 'api-client' | 'channel' | 'channel-manager' | 'client' | 'connection' | 'instance-configuration' | 'message-composer' | 'offline-db' | 'state-store' | 'text-composer' | 'thread' | 'thread-manager' | 'token-manager' | 'upload-manager' | 'utils';
|
|
2
|
+
export type ChatLoggerScope = 'api-client' | 'channel' | 'channel-manager' | 'client' | 'connection' | 'instance-configuration' | 'live-location-manager' | 'message-composer' | 'offline-db' | 'state-store' | 'text-composer' | 'thread' | 'thread-manager' | 'token-manager' | 'upload-manager' | 'utils';
|
|
3
3
|
/** @internal */
|
|
4
4
|
export type ScopedLogger = scopedLogger.Logger<ChatLoggerScope>;
|
|
5
5
|
export { LogLevelEnum } from '@stream-io/logger';
|
|
@@ -128,8 +128,10 @@ export type PaginationQueryParams<Q> = {
|
|
|
128
128
|
silent?: boolean;
|
|
129
129
|
/**
|
|
130
130
|
* Whether the page's interval becomes the active one and the state is published. Default: true.
|
|
131
|
-
*
|
|
132
|
-
*
|
|
131
|
+
* With `false` the page is only stored. It is still published when it lands in the active
|
|
132
|
+
* interval, or when it is an empty first page of a list without items (not at a caller's
|
|
133
|
+
* `queryShape`, not superseded by a later claim). With `true` the paginator's own page can still
|
|
134
|
+
* be only stored (see `BasePaginator.isPageOnlyStored`).
|
|
133
135
|
*/
|
|
134
136
|
updateState?: boolean;
|
|
135
137
|
};
|
|
@@ -402,6 +404,8 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
402
404
|
/** Canonical, ID-addressable item storage: the single source of truth outside the paginator. */
|
|
403
405
|
protected _itemIndex: ItemIndexApi<T>;
|
|
404
406
|
protected _executeQueryDebounced: DebouncedExecQueryFunction<Q>;
|
|
407
|
+
/** How many times `resetState()` ran, which tells the work started before a reset apart. */
|
|
408
|
+
private _stateResetCount;
|
|
405
409
|
/** Last effective query shape produced by the subclass for the most recent request. */
|
|
406
410
|
protected _lastQueryShape?: Q;
|
|
407
411
|
/** Set by `setItems`, which loads a page (even an empty one) without a query. */
|
|
@@ -572,7 +576,8 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
572
576
|
/**
|
|
573
577
|
* The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
|
|
574
578
|
* besides its page, once the page is placed with `placeParams`. Runs once for every response that
|
|
575
|
-
* arrived, also when
|
|
579
|
+
* arrived, also when placing its page failed or a reset made it ignored (see
|
|
580
|
+
* {@link executeQuery}). Does nothing by default.
|
|
576
581
|
*/
|
|
577
582
|
protected applyQueryResponseRest(_response: R, _placeParams: QueryPagePlacement<Q>): void;
|
|
578
583
|
/**
|
|
@@ -945,11 +950,18 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
945
950
|
}) => Promise<T[] | undefined> | T[] | undefined;
|
|
946
951
|
/**
|
|
947
952
|
* {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
|
|
948
|
-
* error is
|
|
949
|
-
*
|
|
950
|
-
* caller to end the query.
|
|
953
|
+
* error is reported (see {@link reportFailedFetch}). After a `resetState()`
|
|
954
|
+
* (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
|
|
951
955
|
*/
|
|
952
|
-
protected fetchQueryResponseWithRetries(params?: PaginationQueryParams<Q
|
|
956
|
+
protected fetchQueryResponseWithRetries(params?: PaginationQueryParams<Q>, { checkWasStateResetDuringQuery, }?: {
|
|
957
|
+
checkWasStateResetDuringQuery?: () => boolean;
|
|
958
|
+
}): Promise<R | null>;
|
|
959
|
+
/**
|
|
960
|
+
* Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
|
|
961
|
+
* and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
|
|
962
|
+
* and the caller ends the query.
|
|
963
|
+
*/
|
|
964
|
+
private reportFailedFetch;
|
|
953
965
|
/**
|
|
954
966
|
* Runs one query through the query pipeline, step by step:
|
|
955
967
|
*
|
|
@@ -966,9 +978,13 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
966
978
|
* as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
|
|
967
979
|
* rejects the call only with `throwErrors` set.
|
|
968
980
|
*
|
|
969
|
-
*
|
|
970
|
-
*
|
|
971
|
-
*
|
|
981
|
+
* If `resetState()` runs while the query runs, the query is ignored: it places no page, records
|
|
982
|
+
* no error and throws nothing, also with `throwErrors`. The queries started after the reset own
|
|
983
|
+
* the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
|
|
984
|
+
*
|
|
985
|
+
* Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
|
|
986
|
+
* results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
|
|
987
|
+
* is `null` when no page was placed, with `isSuperseded`.
|
|
972
988
|
*
|
|
973
989
|
* @param params - Query parameters.
|
|
974
990
|
* @param params.claimsActiveInterval - Whether the query claims the active interval.
|
|
@@ -987,12 +1003,22 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
987
1003
|
executeQuery(params?: PaginationQueryParams<Q>): Promise<ExecuteQueryReturnValue<T> | void>;
|
|
988
1004
|
/** The steps after {@link prepareQuery} of the query pipeline (see {@link executeQuery}). */
|
|
989
1005
|
private runPreparedQuery;
|
|
1006
|
+
/**
|
|
1007
|
+
* {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
|
|
1008
|
+
* An ignored query reports nothing, so an error here is swallowed.
|
|
1009
|
+
*/
|
|
1010
|
+
private applyResponseRestOfIgnoredQuery;
|
|
990
1011
|
/**
|
|
991
1012
|
* Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
|
|
992
1013
|
* throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
|
|
993
1014
|
* placed with the error in its state, so a caller committing that state keeps the error.
|
|
994
1015
|
*/
|
|
995
1016
|
private reportQueryError;
|
|
1017
|
+
/**
|
|
1018
|
+
* Returns a function telling whether `resetState()` ran since this call. Work started before a
|
|
1019
|
+
* reset uses it to ignore its results instead of writing them into the reset state.
|
|
1020
|
+
*/
|
|
1021
|
+
protected makeStateResetWatcher(): () => boolean;
|
|
996
1022
|
/**
|
|
997
1023
|
* Whether a query claims the active interval by default (see
|
|
998
1024
|
* `PaginationQueryParams.claimsActiveInterval`, which overrides it):
|
|
@@ -1025,6 +1051,27 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
1025
1051
|
* the page with no known place relative to the active interval.
|
|
1026
1052
|
*/
|
|
1027
1053
|
private continuedIntervalIsInactive;
|
|
1054
|
+
/**
|
|
1055
|
+
* Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
|
|
1056
|
+
* instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
|
|
1057
|
+
* defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
|
|
1058
|
+
*/
|
|
1059
|
+
private emptyPageKeepsLoadedItems;
|
|
1060
|
+
/**
|
|
1061
|
+
* Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
|
|
1062
|
+
* own `updateState: false` query settles a list without items
|
|
1063
|
+
* ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
|
|
1064
|
+
* what the stored page changed.
|
|
1065
|
+
*/
|
|
1066
|
+
private commitsPlacedState;
|
|
1067
|
+
/**
|
|
1068
|
+
* Whether an empty, only-stored first page sets a list without items (`items` undefined) to
|
|
1069
|
+
* `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
|
|
1070
|
+
* Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
|
|
1071
|
+
* list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
|
|
1072
|
+
* owns the list.
|
|
1073
|
+
*/
|
|
1074
|
+
private emptyPageSettlesListWithoutItems;
|
|
1028
1075
|
/** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
|
|
1029
1076
|
private claimIsSuperseded;
|
|
1030
1077
|
/**
|
|
@@ -1042,7 +1089,7 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
1042
1089
|
* database. A page from a query the paginator did not run is placed without any of that, as one
|
|
1043
1090
|
* of the paginator's own queries may still be running.
|
|
1044
1091
|
*/
|
|
1045
|
-
protected placePage(
|
|
1092
|
+
protected placePage(placement: QueryPagePlacement<Q> & {
|
|
1046
1093
|
results: PaginationQueryReturnValue<T>;
|
|
1047
1094
|
}, { endsQuery }: {
|
|
1048
1095
|
endsQuery: boolean;
|
|
@@ -1053,6 +1100,10 @@ export declare abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue
|
|
|
1053
1100
|
*/
|
|
1054
1101
|
private publishStoredPage;
|
|
1055
1102
|
cancelScheduledQuery(): void;
|
|
1103
|
+
/**
|
|
1104
|
+
* Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
|
|
1105
|
+
* ignored (see {@link executeQuery}); a debounced query stays scheduled.
|
|
1106
|
+
*/
|
|
1056
1107
|
resetState(): void;
|
|
1057
1108
|
/**
|
|
1058
1109
|
* Releases this paginator's hold on its item content (unlinks every member ID from the shared
|
|
@@ -121,10 +121,31 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
|
|
|
121
121
|
get effectiveSort(): SortParamRequest[];
|
|
122
122
|
get options(): ChannelOptions | undefined;
|
|
123
123
|
get channelStateOptions(): ChannelStateOptions | undefined;
|
|
124
|
+
/** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
|
|
124
125
|
set staticFilters(filters: ChannelFilters | undefined);
|
|
126
|
+
/** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
|
|
125
127
|
set sort(sort: SortParamRequest[] | undefined);
|
|
128
|
+
/** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
|
|
126
129
|
set options(options: ChannelPaginatorRequestOptions | undefined);
|
|
127
130
|
set channelStateOptions(options: ChannelStateOptions | undefined);
|
|
131
|
+
/**
|
|
132
|
+
* Applies a change to a query input (filters, sort, options) and resets the list with
|
|
133
|
+
* `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
|
|
134
|
+
* whole query before and after, so setting an equal value or only a page-size option keeps the
|
|
135
|
+
* loaded pages.
|
|
136
|
+
*
|
|
137
|
+
* After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
|
|
138
|
+
* query's first page. A query still running for the old query is ignored; a debounced query
|
|
139
|
+
* stays scheduled and runs with the new query.
|
|
140
|
+
*/
|
|
141
|
+
private changeQuery;
|
|
142
|
+
/**
|
|
143
|
+
* Whether the next query has another identity than `queryBefore`
|
|
144
|
+
* (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
|
|
145
|
+
* options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
|
|
146
|
+
* and `member_limit` and `message_limit` (how much of each channel loads).
|
|
147
|
+
*/
|
|
148
|
+
private queryChangeDiscardsPages;
|
|
128
149
|
get sortComparatorFactory(): ChannelSortComparatorFactory | undefined;
|
|
129
150
|
/**
|
|
130
151
|
* Rebuilds the comparator immediately; later rebuilds consult the factory again, so a sort change
|
|
@@ -140,6 +161,17 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
|
|
|
140
161
|
buildQueryFilters: () => ChannelFilters;
|
|
141
162
|
/** Filters items are matched against locally (`matchesFilter`), built from `effectiveFilters`. */
|
|
142
163
|
buildMatchFilters: () => ChannelFilters;
|
|
164
|
+
/**
|
|
165
|
+
* Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
|
|
166
|
+
* server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
|
|
167
|
+
* holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
|
|
168
|
+
* cache stored without it) matches by `staticFilters`.
|
|
169
|
+
*/
|
|
170
|
+
private get awaitsPredefinedFilter();
|
|
171
|
+
/**
|
|
172
|
+
* Whether `channel` belongs to the list. Nothing does while a list with
|
|
173
|
+
* `options.predefined_filter` holds neither a page nor `predefinedFilter`.
|
|
174
|
+
*/
|
|
143
175
|
matchesFilter(channel: Channel): boolean;
|
|
144
176
|
/** Commits the response's `predefined_filter` metadata, or clears it when there is none. */
|
|
145
177
|
protected applyPredefinedFilterResponse(predefinedFilter: ParsedPredefinedFilterResponse | undefined): void;
|
|
@@ -221,6 +253,11 @@ export declare class ChannelPaginator extends BasePaginator<Channel, ChannelQuer
|
|
|
221
253
|
onEntitiesChanged(): void;
|
|
222
254
|
/** Entity-store subscriber: the store removed a channel this list holds (e.g. logout). */
|
|
223
255
|
onEntityRemoved(id: string, channel: unknown): void;
|
|
256
|
+
/**
|
|
257
|
+
* Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
|
|
258
|
+
* no record of queries in progress. A query running meanwhile is ignored; a debounced query
|
|
259
|
+
* stays scheduled.
|
|
260
|
+
*/
|
|
224
261
|
resetState(): void;
|
|
225
262
|
removeItem(params: {
|
|
226
263
|
id?: string;
|
package/package.json
CHANGED
|
@@ -11,6 +11,7 @@ import { StateStore } from '@stream-io/state-store';
|
|
|
11
11
|
import { ConfigController } from './configuration/ConfigController';
|
|
12
12
|
import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
|
|
13
13
|
import { WithSubscriptions } from './utils/WithSubscriptions';
|
|
14
|
+
import { chatLoggerSystem } from './logger';
|
|
14
15
|
import type { StreamChat } from './client';
|
|
15
16
|
import type { Unsubscribe } from '@stream-io/state-store';
|
|
16
17
|
import type {
|
|
@@ -26,13 +27,18 @@ export type WatchLocation = (handler: WatchLocationHandler) => Unsubscribe;
|
|
|
26
27
|
type DeviceIdGenerator = () => string;
|
|
27
28
|
type MessageId = string;
|
|
28
29
|
|
|
30
|
+
const logger = chatLoggerSystem.getLogger('live-location-manager');
|
|
31
|
+
|
|
29
32
|
export type ScheduledLiveLocationSharing = SharedLiveLocationResponse & {
|
|
30
33
|
stopSharingTimeout: ReturnType<typeof setTimeout> | null;
|
|
31
34
|
};
|
|
32
35
|
|
|
33
36
|
export type LiveLocationManagerState = {
|
|
37
|
+
/** Whether the user's active live locations have been loaded from the server. */
|
|
34
38
|
ready: boolean;
|
|
35
39
|
messages: Map<MessageId, ScheduledLiveLocationSharing>;
|
|
40
|
+
/** Error of the last failed load of the active live locations. Cleared by a successful load. */
|
|
41
|
+
lastQueryError?: Error;
|
|
36
42
|
};
|
|
37
43
|
|
|
38
44
|
/** `setTimeout` silently clamps a longer delay to 1 ms, so longer waits are armed in steps. */
|
|
@@ -94,6 +100,14 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
94
100
|
private getDeviceId: DeviceIdGenerator;
|
|
95
101
|
private _deviceId: string;
|
|
96
102
|
private watchLocation: WatchLocation;
|
|
103
|
+
/** The in-flight load of the active live locations, shared by concurrent callers. */
|
|
104
|
+
private stateInitPromise?: Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Ids of live-location messages removed from `state.messages` (stopped, deleted, expired) while
|
|
107
|
+
* `getUserLiveLocations()` is in flight. The response may predate the removal, so its entries
|
|
108
|
+
* for these ids are skipped instead of being tracked again.
|
|
109
|
+
*/
|
|
110
|
+
private unregisteredDuringLoad = new Set<MessageId>();
|
|
97
111
|
|
|
98
112
|
private readonly configController: ConfigController<LiveLocationManagerConfig>;
|
|
99
113
|
private unsubscribeConfiguration?: Unsubscribe;
|
|
@@ -171,9 +185,18 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
171
185
|
this.configController.initialize(config);
|
|
172
186
|
}
|
|
173
187
|
|
|
188
|
+
/**
|
|
189
|
+
* Registers the event subscriptions, then loads the user's active live locations. Registration
|
|
190
|
+
* runs before the first `await`, so each `init()` pairs with one `unregisterSubscriptions()`
|
|
191
|
+
* whether or not the load has finished.
|
|
192
|
+
*
|
|
193
|
+
* Never rejects. A failed load is stored in `state.lastQueryError` and the subscriptions stay
|
|
194
|
+
* registered, so shares started later are still tracked. The next `init()`, position update or
|
|
195
|
+
* `connection.recovered` event retries the load.
|
|
196
|
+
*/
|
|
174
197
|
public async init() {
|
|
175
|
-
await this.assureStateInit();
|
|
176
198
|
this.registerSubscriptions();
|
|
199
|
+
await this.assureStateInit();
|
|
177
200
|
}
|
|
178
201
|
|
|
179
202
|
public registerSubscriptions = () => {
|
|
@@ -219,24 +242,44 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
219
242
|
return this._deviceId;
|
|
220
243
|
}
|
|
221
244
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
245
|
+
/** Loads the active live locations unless already loaded. Never rejects. */
|
|
246
|
+
private assureStateInit(): Promise<void> {
|
|
247
|
+
if (this.stateIsReady) return Promise.resolve();
|
|
248
|
+
|
|
249
|
+
this.stateInitPromise ??= this.loadState().finally(() => {
|
|
250
|
+
this.stateInitPromise = undefined;
|
|
251
|
+
this.unregisteredDuringLoad.clear();
|
|
252
|
+
});
|
|
253
|
+
return this.stateInitPromise;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async loadState() {
|
|
257
|
+
try {
|
|
258
|
+
const { active_live_locations } = await this.client.getUserLiveLocations();
|
|
259
|
+
this.state.next((currentValue) => {
|
|
260
|
+
// Events received while the request was in flight are at least as recent as the snapshot:
|
|
261
|
+
// shares they registered are kept as they are, and shares they unregistered stay out.
|
|
262
|
+
const messages = new Map(currentValue.messages);
|
|
263
|
+
for (const location of active_live_locations.filter(isTrackableLocation)) {
|
|
264
|
+
if (
|
|
265
|
+
messages.has(location.message_id) ||
|
|
266
|
+
this.unregisteredDuringLoad.has(location.message_id)
|
|
267
|
+
)
|
|
268
|
+
continue;
|
|
269
|
+
messages.set(location.message_id, {
|
|
230
270
|
...location,
|
|
231
271
|
stopSharingTimeout: this.scheduleStopSharing(
|
|
232
272
|
location.message_id,
|
|
233
273
|
location.end_at,
|
|
234
274
|
),
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
})
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
return { ...currentValue, messages, ready: true, lastQueryError: undefined };
|
|
278
|
+
});
|
|
279
|
+
} catch (error) {
|
|
280
|
+
logger.warn('Failed to load the active live locations', error);
|
|
281
|
+
this.state.partialNext({ lastQueryError: error as Error });
|
|
282
|
+
}
|
|
240
283
|
}
|
|
241
284
|
|
|
242
285
|
private subscribeTargetMessagesChange() {
|
|
@@ -319,11 +362,13 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
319
362
|
if (event.type === 'live_location_sharing.started') {
|
|
320
363
|
this.registerMessage(event.message);
|
|
321
364
|
} else if (event.type === 'message.updated') {
|
|
322
|
-
|
|
323
|
-
|
|
365
|
+
// A share stopped on another device arrives here with an `end_at` in the past.
|
|
366
|
+
// Unregistered even when not tracked yet, so a load in flight does not re-add it.
|
|
367
|
+
if (isValidLiveLocationMessage(event.message)) {
|
|
368
|
+
this.registerMessage(event.message);
|
|
369
|
+
} else {
|
|
324
370
|
this.unregisterMessages([event.message.id]);
|
|
325
371
|
}
|
|
326
|
-
this.registerMessage(event.message);
|
|
327
372
|
} else {
|
|
328
373
|
this.unregisterMessages([event.message.id]);
|
|
329
374
|
}
|
|
@@ -334,6 +379,10 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
334
379
|
|
|
335
380
|
this.unregisterMessages([event.live_location?.message_id]);
|
|
336
381
|
}),
|
|
382
|
+
// Retries a failed load once the connection is back. No-op once the state is loaded.
|
|
383
|
+
this.client.on('connection.recovered', () => {
|
|
384
|
+
void this.assureStateInit();
|
|
385
|
+
}),
|
|
337
386
|
];
|
|
338
387
|
|
|
339
388
|
return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
|
|
@@ -392,6 +441,9 @@ export class LiveLocationManager extends WithSubscriptions {
|
|
|
392
441
|
}
|
|
393
442
|
|
|
394
443
|
private unregisterMessages(messageIds: string[]) {
|
|
444
|
+
if (this.stateInitPromise) {
|
|
445
|
+
messageIds.forEach((messageId) => this.unregisteredDuringLoad.add(messageId));
|
|
446
|
+
}
|
|
395
447
|
const messages = this.messages;
|
|
396
448
|
const removedMessages = new Set(messageIds);
|
|
397
449
|
const newMessages = new Map(
|