incyclist-services 1.9.13 → 1.9.15

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.
@@ -48,6 +48,8 @@ const utils_1 = require("../../utils");
48
48
  const active_rides_1 = require("../base/api/active-rides");
49
49
  const ride_1 = require("../ride");
50
50
  const mq_1 = require("./mq");
51
+ const LOOKUP_BACKOFF_START = 30_000;
52
+ const LOOKUP_BACKOFF_MAX = 300_000;
51
53
  let ActiveRidesService = (() => {
52
54
  let _classDecorators = [types_1.Singleton];
53
55
  let _classDescriptor;
@@ -101,6 +103,8 @@ let ActiveRidesService = (() => {
101
103
  routesStats = [];
102
104
  routeListSessions = new Map();
103
105
  isSubscribedRouteListEvents = false;
106
+ lookupsInFlight = new Map();
107
+ lookupBackoff = new Map();
104
108
  activityEventHandlers = {
105
109
  update: this.onActivityUpdateEvent.bind(this),
106
110
  start: this.onActivityStartEvent.bind(this),
@@ -762,7 +766,8 @@ let ActiveRidesService = (() => {
762
766
  this.logEvent({ message: 'group ride user joined', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
763
767
  }
764
768
  if (!payload.user) {
765
- this.getRemoteActivityDetails(session).catch(err => { this.logError(err, 'onActivityStartEvent'); });
769
+ this.lookupRemoteRider(session).then(resolved => { if (resolved)
770
+ this.observer?.emit('update', this.getDisplayProps()); }).catch(err => { this.logError(err, 'onActivityStartEvent'); });
766
771
  }
767
772
  this.observer.emit('update', this.getDisplayProps());
768
773
  }
@@ -788,9 +793,6 @@ let ActiveRidesService = (() => {
788
793
  localItem.bike = item.bike;
789
794
  localItem.ride = item.ride;
790
795
  }
791
- else {
792
- this.addActiveRide(item);
793
- }
794
796
  return item;
795
797
  }
796
798
  publishUpdateEvent(payload) {
@@ -803,50 +805,64 @@ let ActiveRidesService = (() => {
803
805
  try {
804
806
  if (session === this.session)
805
807
  return;
806
- const others = this.others ?? [];
807
- const existing = others.find(ar => ar.sessionId === session);
808
808
  const prevActive = this.others?.length;
809
- if (existing?.user) {
810
- existing.currentPosition = payload.position;
811
- existing.currentDuration = payload.duration;
812
- existing.currentPower = payload.power;
813
- existing.currentRideDistance = payload.rideDistance;
814
- existing.currentSpeed = payload.speed;
815
- existing.currentLap = payload.lap;
816
- existing.tsLastUpdate = Date.now();
817
- }
818
- else {
819
- const item = await this.getRemoteActivityDetails(session);
820
- if (!item) {
821
- const entry = {
822
- id: Date.now().toString(),
823
- tsLastUpdate: Date.now(),
824
- sessionId: session,
825
- currentPosition: payload.position,
826
- currentDuration: payload.duration,
827
- currentPower: payload.power,
828
- currentRideDistance: payload.rideDistance,
829
- currentSpeed: payload.speed,
830
- currentLap: payload.lap
831
- };
832
- if (!existing) {
833
- this.addActiveRide(entry);
834
- }
835
- }
809
+ let existing = (this.others ?? []).find(ar => ar.sessionId === session);
810
+ const isNew = !existing;
811
+ if (!existing) {
812
+ existing = { id: Date.now().toString(), sessionId: session };
813
+ this.addActiveRide(existing);
836
814
  this.isStarted = true;
837
- const remote = (item === undefined || item === null) ? { session } : { uuid: item.user?.id, session: item.sessionId };
838
- if (prevActive === 0) {
839
- this.logEvent({ message: 'group ride started', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
840
- }
841
- else {
842
- this.logEvent({ message: 'group ride user joined', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
843
- }
844
815
  }
816
+ this.applyLiveData(existing, payload);
817
+ if (isNew)
818
+ this.logJoined(prevActive, { session });
845
819
  this.observer.emit('update', this.getDisplayProps());
820
+ if (!existing.user) {
821
+ const resolved = await this.lookupRemoteRider(session);
822
+ if (resolved)
823
+ this.observer.emit('update', this.getDisplayProps());
824
+ }
846
825
  }
847
826
  catch (err) {
848
- this.logError(err, 'onActivityStartEvent');
849
- }
827
+ this.logError(err, 'onActivityUpdateEvent');
828
+ }
829
+ }
830
+ applyLiveData(entry, payload) {
831
+ entry.currentPosition = payload.position;
832
+ entry.currentDuration = payload.duration;
833
+ entry.currentPower = payload.power;
834
+ entry.currentRideDistance = payload.rideDistance;
835
+ entry.currentSpeed = payload.speed;
836
+ entry.currentLap = payload.lap;
837
+ entry.tsLastUpdate = Date.now();
838
+ }
839
+ logJoined(prevActive, remote) {
840
+ const message = prevActive === 0 ? 'group ride started' : 'group ride user joined';
841
+ this.logEvent({ message, active: this.others.length + 1, activityId: this.activity?.id, route: this.activity?.route?.title, routeHash: this.getRouteHash(), remote });
842
+ }
843
+ async lookupRemoteRider(session) {
844
+ const inFlight = this.lookupsInFlight.get(session);
845
+ if (inFlight !== undefined)
846
+ return inFlight;
847
+ const backoff = this.lookupBackoff.get(session);
848
+ if (backoff && Date.now() < backoff.until)
849
+ return false;
850
+ const promise = this.getRemoteActivityDetails(session)
851
+ .then(item => item?.user !== undefined && item?.user !== null)
852
+ .catch(err => { this.logError(err, 'lookupRemoteRider'); return false; })
853
+ .then(resolved => {
854
+ if (resolved) {
855
+ this.lookupBackoff.delete(session);
856
+ }
857
+ else {
858
+ const delay = Math.min((backoff?.delay ?? LOOKUP_BACKOFF_START / 2) * 2, LOOKUP_BACKOFF_MAX);
859
+ this.lookupBackoff.set(session, { delay, until: Date.now() + delay });
860
+ }
861
+ return resolved;
862
+ })
863
+ .finally(() => { this.lookupsInFlight.delete(session); });
864
+ this.lookupsInFlight.set(session, promise);
865
+ return promise;
850
866
  }
851
867
  addActiveRide(ride) {
852
868
  if (!this.others)
@@ -864,10 +880,11 @@ let ActiveRidesService = (() => {
864
880
  return;
865
881
  if (!this.others?.length)
866
882
  return;
867
- const idx = this.others.findIndex(ar => ar.sessionId === session);
868
- if (idx === -1)
883
+ const remaining = this.others.filter(ar => ar.sessionId !== session);
884
+ if (remaining.length === this.others.length)
869
885
  return;
870
- this.others.splice(idx, 1);
886
+ this.others = remaining;
887
+ this.lookupBackoff.delete(session);
871
888
  this.observer.emit('update', this.getDisplayProps());
872
889
  if (!this.isStarted)
873
890
  return;
@@ -909,6 +926,9 @@ let ActiveRidesService = (() => {
909
926
  this.isStarted = false;
910
927
  this.getMessageQueue().unsubscribeAll();
911
928
  this.isSubscribed = false;
929
+ this.isSubscribedRouteListEvents = false;
930
+ this.lookupsInFlight.clear();
931
+ this.lookupBackoff.clear();
912
932
  this.observer.stop();
913
933
  }
914
934
  getOnlineStatusMonitoring() {
@@ -262,8 +262,7 @@ let ActivityListService = (() => {
262
262
  await activity.load();
263
263
  return new Promise(done => {
264
264
  const emitUpdate = async (update) => {
265
- this.exports = await this.selected.getExports();
266
- this.emitSelected('updated');
265
+ await this.refreshExports();
267
266
  if (update.status === 'done')
268
267
  done(update.success);
269
268
  };
@@ -287,9 +286,8 @@ let ActivityListService = (() => {
287
286
  }
288
287
  }
289
288
  };
290
- const emitExportUpdate = async (update) => {
291
- this.exports = await this.selected.getExports();
292
- this.emitSelected('updated');
289
+ const emitExportUpdate = async () => {
290
+ await this.refreshExports();
293
291
  };
294
292
  const observer = new observer_1.Observer();
295
293
  observer.on('upload', emitUploadUpdate);
@@ -431,7 +429,19 @@ let ActivityListService = (() => {
431
429
  };
432
430
  return props;
433
431
  }
432
+ async refreshExports() {
433
+ const selected = this.selected;
434
+ if (!selected)
435
+ return;
436
+ const exports = await selected.getExports();
437
+ if (!this.selected)
438
+ return;
439
+ this.exports = exports;
440
+ this.emitSelected('updated');
441
+ }
434
442
  emitSelected(event) {
443
+ if (!this.selected)
444
+ return;
435
445
  const displayProps = this.getSelectedActivityDisplayProps();
436
446
  this.getObserver()?.emit(event, displayProps);
437
447
  }
@@ -82,6 +82,7 @@ let DeviceRideService = (() => {
82
82
  initizialized = __runInitializers(this, _instanceExtraInitializers);
83
83
  adapters;
84
84
  rideAdapters;
85
+ healthChecks = new Set();
85
86
  startPromises;
86
87
  data = {};
87
88
  simulatorEnforced;
@@ -702,7 +703,7 @@ let DeviceRideService = (() => {
702
703
  ai.dataStatus = 'amber';
703
704
  if (isRed)
704
705
  ai.dataStatus = 'red';
705
- if (ai.isHealthy && (isAmber || isRed)) {
706
+ if (ai.isHealthy && (isAmber || isRed) && !ai.adapter.isReconnecting?.()) {
706
707
  ai.isHealthy = false;
707
708
  this.logEvent({ message: 'device unhealthy', device: ai.adapter.getUniqueName(), udid: ai.udid, noDataSince: (tsNow - tsLastData), tsLastData: new Date(tsLastData).toISOString() });
708
709
  this.prepareReconnect(ai).catch(err => { this.logError(err, 'startHealthCheck'); });
@@ -723,6 +724,7 @@ let DeviceRideService = (() => {
723
724
  if (ai.adapter.getInterface() === 'simulator')
724
725
  return;
725
726
  ai.ivToCheck = setInterval(() => { check(); }, 1000);
727
+ this.healthChecks.add(ai);
726
728
  ai.isHealthy = true;
727
729
  ai.isRestarting = false;
728
730
  if (ai.dataStatus !== undefined && ai.dataStatus !== 'green') {
@@ -747,6 +749,7 @@ let DeviceRideService = (() => {
747
749
  clearInterval(ai.ivToCheck);
748
750
  delete ai.ivToCheck;
749
751
  delete ai.isHealthy;
752
+ this.healthChecks.delete(ai);
750
753
  this.removeOnDatahandler(ai);
751
754
  this.lastDataInfo = {};
752
755
  }
@@ -760,16 +763,20 @@ let DeviceRideService = (() => {
760
763
  this.logEvent({ message: 'skipped reconnect - device already restarting', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid, noDataSince: (tsNow - tsLastData), tsLastData: tsLastDataStr });
761
764
  return;
762
765
  }
766
+ if (unhealthy.adapter.isReconnecting?.()) {
767
+ this.logEvent({ message: 'skipped reconnect - device is reconnecting', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid, noDataSince: (tsNow - tsLastData), tsLastData: tsLastDataStr });
768
+ return;
769
+ }
763
770
  unhealthy.isRestarting = true;
764
771
  unhealthy.isHealthy = false;
765
- const ifName = unhealthy.adapter.getInterface();
766
- const adapters = this.rideAdapters?.filter(ai => ai.adapter.getInterface() === ifName);
767
- const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
768
- this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
769
- noDataSince: (tsNow - tsLastData),
770
- tsLastData: tsLastDataStr, stillHealthy: stillHealthy?.length, onSameInterface: adapters.length });
771
772
  try {
772
- if (!stillHealthy?.length && adapters.length > 1 && ifName !== 'ble') {
773
+ const ifName = unhealthy.adapter.getInterface();
774
+ const adapters = (this.rideAdapters ?? [unhealthy]).filter(ai => ai.adapter.getInterface() === ifName);
775
+ const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
776
+ this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
777
+ noDataSince: (tsNow - tsLastData),
778
+ tsLastData: tsLastDataStr, stillHealthy: stillHealthy.length, onSameInterface: adapters.length });
779
+ if (!stillHealthy.length && adapters.length > 1 && ifName !== 'ble') {
773
780
  await this.reconnectInterface(ifName, adapters);
774
781
  }
775
782
  else {
@@ -779,7 +786,9 @@ let DeviceRideService = (() => {
779
786
  catch (err) {
780
787
  this.logError(err, 'prepareReconnect');
781
788
  }
782
- unhealthy.isRestarting = false;
789
+ finally {
790
+ unhealthy.isRestarting = false;
791
+ }
783
792
  }
784
793
  async reconnectInterface(ifName, adapters) {
785
794
  if (this.reconnectBusy) {
@@ -1003,6 +1012,7 @@ let DeviceRideService = (() => {
1003
1012
  this.logEvent({ message: 'stop device', udid });
1004
1013
  const adapters = this.rideAdapters;
1005
1014
  this.emit('stop-ride');
1015
+ this.stopHealthChecks(udid);
1006
1016
  const promises = adapters?.filter(ai => udid ? ai.udid === udid : true)
1007
1017
  .map(ai => {
1008
1018
  this.stopHealthCheck(ai);
@@ -1015,6 +1025,12 @@ let DeviceRideService = (() => {
1015
1025
  this.simulatorEnforced = false;
1016
1026
  return true;
1017
1027
  }
1028
+ stopHealthChecks(udid) {
1029
+ for (const ai of this.healthChecks) {
1030
+ if (!udid || ai.udid === udid)
1031
+ this.stopHealthCheck(ai);
1032
+ }
1033
+ }
1018
1034
  async resetLimits() {
1019
1035
  try {
1020
1036
  const mode = this.getCyclingMode();
@@ -1,4 +1,11 @@
1
1
  "use strict";
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
2
9
  var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
10
  function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
11
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
@@ -26,13 +33,6 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
26
33
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
34
  done = true;
28
35
  };
29
- var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
- var useValue = arguments.length > 2;
31
- for (var i = 0; i < initializers.length; i++) {
32
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
- }
34
- return useValue ? value : void 0;
35
- };
36
36
  var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
38
38
  };
@@ -40,6 +40,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
40
40
  exports.getCountries = exports.Countries = void 0;
41
41
  const service_1 = require("../../base/service");
42
42
  const types_1 = require("../../base/types");
43
+ const decorators_1 = require("../../base/decorators");
43
44
  const countries_json_1 = __importDefault(require("./countries.json"));
44
45
  const factory_1 = require("../../routes/base/api/factory");
45
46
  let Countries = (() => {
@@ -48,16 +49,20 @@ let Countries = (() => {
48
49
  let _classExtraInitializers = [];
49
50
  let _classThis;
50
51
  let _classSuper = service_1.IncyclistService;
52
+ let _instanceExtraInitializers = [];
53
+ let _getIncyclistRoutesApi_decorators;
51
54
  var Countries = class extends _classSuper {
52
55
  static { _classThis = this; }
53
56
  static {
54
57
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
58
+ _getIncyclistRoutesApi_decorators = [decorators_1.Injectable];
59
+ __esDecorate(this, null, _getIncyclistRoutesApi_decorators, { kind: "method", name: "getIncyclistRoutesApi", static: false, private: false, access: { has: obj => "getIncyclistRoutesApi" in obj, get: obj => obj.getIncyclistRoutesApi }, metadata: _metadata }, null, _instanceExtraInitializers);
55
60
  __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
56
61
  Countries = _classThis = _classDescriptor.value;
57
62
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
58
63
  __runInitializers(_classThis, _classExtraInitializers);
59
64
  }
60
- language;
65
+ language = __runInitializers(this, _instanceExtraInitializers);
61
66
  countryLists;
62
67
  constructor() {
63
68
  super('Countries');
@@ -91,9 +96,12 @@ let Countries = (() => {
91
96
  return countries.map(c => this.getIsoFromCountry(c, locale));
92
97
  }
93
98
  async getIsoFromLatLng(point) {
94
- const api = (0, factory_1.useIncyclistRoutesApi)().create();
99
+ const api = this.getIncyclistRoutesApi().create();
95
100
  return api.getCountry(point);
96
101
  }
102
+ getIncyclistRoutesApi() {
103
+ return (0, factory_1.useIncyclistRoutesApi)();
104
+ }
97
105
  };
98
106
  return Countries = _classThis;
99
107
  })();
@@ -55,6 +55,11 @@ const verify = (route) => {
55
55
  fixMissingRouteDistances(route.points);
56
56
  }
57
57
  };
58
+ const isNoResponseError = (err) => {
59
+ return err?.message === 'Network Error' ||
60
+ err?.code === 'ERR_NETWORK' ||
61
+ (err?.isAxiosError === true && !err.response);
62
+ };
58
63
  let IncyclistRoutesApi = (() => {
59
64
  let _instanceExtraInitializers = [];
60
65
  let _getUserSettings_decorators;
@@ -170,6 +175,10 @@ let IncyclistRoutesApi = (() => {
170
175
  return res.data.country?.toUpperCase();
171
176
  }
172
177
  catch (err) {
178
+ if (isNoResponseError(err)) {
179
+ this.logger.logEvent({ message: 'getCountry failed: no response from server', reason: err.message });
180
+ return;
181
+ }
173
182
  this.logError(err, 'getCountry');
174
183
  }
175
184
  }
@@ -82,6 +82,7 @@ let FreeRideService = (() => {
82
82
  initialized = false;
83
83
  ivInit;
84
84
  cntInitRetry = 0;
85
+ pendingEnsure;
85
86
  rideSeq = 0;
86
87
  selectedBy = 'auto';
87
88
  startSource = 'default';
@@ -115,6 +116,18 @@ let FreeRideService = (() => {
115
116
  isInitialized() {
116
117
  return this.initialized;
117
118
  }
119
+ async ensureInitialized() {
120
+ if (this.initialized)
121
+ return true;
122
+ if (!this.pendingEnsure) {
123
+ this.logEvent({ message: 'init free ride service on demand' });
124
+ this.pendingEnsure = this.selectStartPosition()
125
+ .catch(err => { this.logError(err, 'ensureInitialized'); })
126
+ .then(() => this.initialized)
127
+ .finally(() => { delete this.pendingEnsure; });
128
+ }
129
+ return this.pendingEnsure;
130
+ }
118
131
  async selectStartPosition(position, opts) {
119
132
  const rideSeq = this.rideSeq;
120
133
  const keepSource = !position && (this.startSource === 'search' || this.startSource === 'map');
@@ -756,6 +756,9 @@ let RouteListService = (() => {
756
756
  isFreeRideSupported() {
757
757
  return this.getFreeRideService().isInitialized();
758
758
  }
759
+ async ensureFreeRideSupported() {
760
+ return await this.getFreeRideService().ensureInitialized();
761
+ }
759
762
  addRoute(route, source = 'system') {
760
763
  const existing = source === 'system' ? this.getRoute(route.description.id) :
761
764
  this.routes.find(r => r.description?.id === route.description.id);
@@ -45,6 +45,8 @@ import { waitNextTick } from "../../utils";
45
45
  import { IncyclistActiveRidesApi } from "../base/api/active-rides";
46
46
  import { useActivityRide } from "../ride";
47
47
  import { ActiveRideListMessageQueue } from "./mq";
48
+ const LOOKUP_BACKOFF_START = 30_000;
49
+ const LOOKUP_BACKOFF_MAX = 300_000;
48
50
  let ActiveRidesService = (() => {
49
51
  let _classDecorators = [Singleton];
50
52
  let _classDescriptor;
@@ -98,6 +100,8 @@ let ActiveRidesService = (() => {
98
100
  routesStats = [];
99
101
  routeListSessions = new Map();
100
102
  isSubscribedRouteListEvents = false;
103
+ lookupsInFlight = new Map();
104
+ lookupBackoff = new Map();
101
105
  activityEventHandlers = {
102
106
  update: this.onActivityUpdateEvent.bind(this),
103
107
  start: this.onActivityStartEvent.bind(this),
@@ -759,7 +763,8 @@ let ActiveRidesService = (() => {
759
763
  this.logEvent({ message: 'group ride user joined', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
760
764
  }
761
765
  if (!payload.user) {
762
- this.getRemoteActivityDetails(session).catch(err => { this.logError(err, 'onActivityStartEvent'); });
766
+ this.lookupRemoteRider(session).then(resolved => { if (resolved)
767
+ this.observer?.emit('update', this.getDisplayProps()); }).catch(err => { this.logError(err, 'onActivityStartEvent'); });
763
768
  }
764
769
  this.observer.emit('update', this.getDisplayProps());
765
770
  }
@@ -785,9 +790,6 @@ let ActiveRidesService = (() => {
785
790
  localItem.bike = item.bike;
786
791
  localItem.ride = item.ride;
787
792
  }
788
- else {
789
- this.addActiveRide(item);
790
- }
791
793
  return item;
792
794
  }
793
795
  publishUpdateEvent(payload) {
@@ -800,50 +802,64 @@ let ActiveRidesService = (() => {
800
802
  try {
801
803
  if (session === this.session)
802
804
  return;
803
- const others = this.others ?? [];
804
- const existing = others.find(ar => ar.sessionId === session);
805
805
  const prevActive = this.others?.length;
806
- if (existing?.user) {
807
- existing.currentPosition = payload.position;
808
- existing.currentDuration = payload.duration;
809
- existing.currentPower = payload.power;
810
- existing.currentRideDistance = payload.rideDistance;
811
- existing.currentSpeed = payload.speed;
812
- existing.currentLap = payload.lap;
813
- existing.tsLastUpdate = Date.now();
814
- }
815
- else {
816
- const item = await this.getRemoteActivityDetails(session);
817
- if (!item) {
818
- const entry = {
819
- id: Date.now().toString(),
820
- tsLastUpdate: Date.now(),
821
- sessionId: session,
822
- currentPosition: payload.position,
823
- currentDuration: payload.duration,
824
- currentPower: payload.power,
825
- currentRideDistance: payload.rideDistance,
826
- currentSpeed: payload.speed,
827
- currentLap: payload.lap
828
- };
829
- if (!existing) {
830
- this.addActiveRide(entry);
831
- }
832
- }
806
+ let existing = (this.others ?? []).find(ar => ar.sessionId === session);
807
+ const isNew = !existing;
808
+ if (!existing) {
809
+ existing = { id: Date.now().toString(), sessionId: session };
810
+ this.addActiveRide(existing);
833
811
  this.isStarted = true;
834
- const remote = (item === undefined || item === null) ? { session } : { uuid: item.user?.id, session: item.sessionId };
835
- if (prevActive === 0) {
836
- this.logEvent({ message: 'group ride started', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
837
- }
838
- else {
839
- this.logEvent({ message: 'group ride user joined', active: this.others.length + 1, activityId: this.activity?.id, route: this.activity.route?.title, routeHash: this.getRouteHash(), remote });
840
- }
841
812
  }
813
+ this.applyLiveData(existing, payload);
814
+ if (isNew)
815
+ this.logJoined(prevActive, { session });
842
816
  this.observer.emit('update', this.getDisplayProps());
817
+ if (!existing.user) {
818
+ const resolved = await this.lookupRemoteRider(session);
819
+ if (resolved)
820
+ this.observer.emit('update', this.getDisplayProps());
821
+ }
843
822
  }
844
823
  catch (err) {
845
- this.logError(err, 'onActivityStartEvent');
846
- }
824
+ this.logError(err, 'onActivityUpdateEvent');
825
+ }
826
+ }
827
+ applyLiveData(entry, payload) {
828
+ entry.currentPosition = payload.position;
829
+ entry.currentDuration = payload.duration;
830
+ entry.currentPower = payload.power;
831
+ entry.currentRideDistance = payload.rideDistance;
832
+ entry.currentSpeed = payload.speed;
833
+ entry.currentLap = payload.lap;
834
+ entry.tsLastUpdate = Date.now();
835
+ }
836
+ logJoined(prevActive, remote) {
837
+ const message = prevActive === 0 ? 'group ride started' : 'group ride user joined';
838
+ this.logEvent({ message, active: this.others.length + 1, activityId: this.activity?.id, route: this.activity?.route?.title, routeHash: this.getRouteHash(), remote });
839
+ }
840
+ async lookupRemoteRider(session) {
841
+ const inFlight = this.lookupsInFlight.get(session);
842
+ if (inFlight !== undefined)
843
+ return inFlight;
844
+ const backoff = this.lookupBackoff.get(session);
845
+ if (backoff && Date.now() < backoff.until)
846
+ return false;
847
+ const promise = this.getRemoteActivityDetails(session)
848
+ .then(item => item?.user !== undefined && item?.user !== null)
849
+ .catch(err => { this.logError(err, 'lookupRemoteRider'); return false; })
850
+ .then(resolved => {
851
+ if (resolved) {
852
+ this.lookupBackoff.delete(session);
853
+ }
854
+ else {
855
+ const delay = Math.min((backoff?.delay ?? LOOKUP_BACKOFF_START / 2) * 2, LOOKUP_BACKOFF_MAX);
856
+ this.lookupBackoff.set(session, { delay, until: Date.now() + delay });
857
+ }
858
+ return resolved;
859
+ })
860
+ .finally(() => { this.lookupsInFlight.delete(session); });
861
+ this.lookupsInFlight.set(session, promise);
862
+ return promise;
847
863
  }
848
864
  addActiveRide(ride) {
849
865
  if (!this.others)
@@ -861,10 +877,11 @@ let ActiveRidesService = (() => {
861
877
  return;
862
878
  if (!this.others?.length)
863
879
  return;
864
- const idx = this.others.findIndex(ar => ar.sessionId === session);
865
- if (idx === -1)
880
+ const remaining = this.others.filter(ar => ar.sessionId !== session);
881
+ if (remaining.length === this.others.length)
866
882
  return;
867
- this.others.splice(idx, 1);
883
+ this.others = remaining;
884
+ this.lookupBackoff.delete(session);
868
885
  this.observer.emit('update', this.getDisplayProps());
869
886
  if (!this.isStarted)
870
887
  return;
@@ -906,6 +923,9 @@ let ActiveRidesService = (() => {
906
923
  this.isStarted = false;
907
924
  this.getMessageQueue().unsubscribeAll();
908
925
  this.isSubscribed = false;
926
+ this.isSubscribedRouteListEvents = false;
927
+ this.lookupsInFlight.clear();
928
+ this.lookupBackoff.clear();
909
929
  this.observer.stop();
910
930
  }
911
931
  getOnlineStatusMonitoring() {
@@ -259,8 +259,7 @@ let ActivityListService = (() => {
259
259
  await activity.load();
260
260
  return new Promise(done => {
261
261
  const emitUpdate = async (update) => {
262
- this.exports = await this.selected.getExports();
263
- this.emitSelected('updated');
262
+ await this.refreshExports();
264
263
  if (update.status === 'done')
265
264
  done(update.success);
266
265
  };
@@ -284,9 +283,8 @@ let ActivityListService = (() => {
284
283
  }
285
284
  }
286
285
  };
287
- const emitExportUpdate = async (update) => {
288
- this.exports = await this.selected.getExports();
289
- this.emitSelected('updated');
286
+ const emitExportUpdate = async () => {
287
+ await this.refreshExports();
290
288
  };
291
289
  const observer = new Observer();
292
290
  observer.on('upload', emitUploadUpdate);
@@ -428,7 +426,19 @@ let ActivityListService = (() => {
428
426
  };
429
427
  return props;
430
428
  }
429
+ async refreshExports() {
430
+ const selected = this.selected;
431
+ if (!selected)
432
+ return;
433
+ const exports = await selected.getExports();
434
+ if (!this.selected)
435
+ return;
436
+ this.exports = exports;
437
+ this.emitSelected('updated');
438
+ }
431
439
  emitSelected(event) {
440
+ if (!this.selected)
441
+ return;
432
442
  const displayProps = this.getSelectedActivityDisplayProps();
433
443
  this.getObserver()?.emit(event, displayProps);
434
444
  }
@@ -76,6 +76,7 @@ let DeviceRideService = (() => {
76
76
  initizialized = __runInitializers(this, _instanceExtraInitializers);
77
77
  adapters;
78
78
  rideAdapters;
79
+ healthChecks = new Set();
79
80
  startPromises;
80
81
  data = {};
81
82
  simulatorEnforced;
@@ -696,7 +697,7 @@ let DeviceRideService = (() => {
696
697
  ai.dataStatus = 'amber';
697
698
  if (isRed)
698
699
  ai.dataStatus = 'red';
699
- if (ai.isHealthy && (isAmber || isRed)) {
700
+ if (ai.isHealthy && (isAmber || isRed) && !ai.adapter.isReconnecting?.()) {
700
701
  ai.isHealthy = false;
701
702
  this.logEvent({ message: 'device unhealthy', device: ai.adapter.getUniqueName(), udid: ai.udid, noDataSince: (tsNow - tsLastData), tsLastData: new Date(tsLastData).toISOString() });
702
703
  this.prepareReconnect(ai).catch(err => { this.logError(err, 'startHealthCheck'); });
@@ -717,6 +718,7 @@ let DeviceRideService = (() => {
717
718
  if (ai.adapter.getInterface() === 'simulator')
718
719
  return;
719
720
  ai.ivToCheck = setInterval(() => { check(); }, 1000);
721
+ this.healthChecks.add(ai);
720
722
  ai.isHealthy = true;
721
723
  ai.isRestarting = false;
722
724
  if (ai.dataStatus !== undefined && ai.dataStatus !== 'green') {
@@ -741,6 +743,7 @@ let DeviceRideService = (() => {
741
743
  clearInterval(ai.ivToCheck);
742
744
  delete ai.ivToCheck;
743
745
  delete ai.isHealthy;
746
+ this.healthChecks.delete(ai);
744
747
  this.removeOnDatahandler(ai);
745
748
  this.lastDataInfo = {};
746
749
  }
@@ -754,16 +757,20 @@ let DeviceRideService = (() => {
754
757
  this.logEvent({ message: 'skipped reconnect - device already restarting', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid, noDataSince: (tsNow - tsLastData), tsLastData: tsLastDataStr });
755
758
  return;
756
759
  }
760
+ if (unhealthy.adapter.isReconnecting?.()) {
761
+ this.logEvent({ message: 'skipped reconnect - device is reconnecting', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid, noDataSince: (tsNow - tsLastData), tsLastData: tsLastDataStr });
762
+ return;
763
+ }
757
764
  unhealthy.isRestarting = true;
758
765
  unhealthy.isHealthy = false;
759
- const ifName = unhealthy.adapter.getInterface();
760
- const adapters = this.rideAdapters?.filter(ai => ai.adapter.getInterface() === ifName);
761
- const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
762
- this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
763
- noDataSince: (tsNow - tsLastData),
764
- tsLastData: tsLastDataStr, stillHealthy: stillHealthy?.length, onSameInterface: adapters.length });
765
766
  try {
766
- if (!stillHealthy?.length && adapters.length > 1 && ifName !== 'ble') {
767
+ const ifName = unhealthy.adapter.getInterface();
768
+ const adapters = (this.rideAdapters ?? [unhealthy]).filter(ai => ai.adapter.getInterface() === ifName);
769
+ const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
770
+ this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
771
+ noDataSince: (tsNow - tsLastData),
772
+ tsLastData: tsLastDataStr, stillHealthy: stillHealthy.length, onSameInterface: adapters.length });
773
+ if (!stillHealthy.length && adapters.length > 1 && ifName !== 'ble') {
767
774
  await this.reconnectInterface(ifName, adapters);
768
775
  }
769
776
  else {
@@ -773,7 +780,9 @@ let DeviceRideService = (() => {
773
780
  catch (err) {
774
781
  this.logError(err, 'prepareReconnect');
775
782
  }
776
- unhealthy.isRestarting = false;
783
+ finally {
784
+ unhealthy.isRestarting = false;
785
+ }
777
786
  }
778
787
  async reconnectInterface(ifName, adapters) {
779
788
  if (this.reconnectBusy) {
@@ -997,6 +1006,7 @@ let DeviceRideService = (() => {
997
1006
  this.logEvent({ message: 'stop device', udid });
998
1007
  const adapters = this.rideAdapters;
999
1008
  this.emit('stop-ride');
1009
+ this.stopHealthChecks(udid);
1000
1010
  const promises = adapters?.filter(ai => udid ? ai.udid === udid : true)
1001
1011
  .map(ai => {
1002
1012
  this.stopHealthCheck(ai);
@@ -1009,6 +1019,12 @@ let DeviceRideService = (() => {
1009
1019
  this.simulatorEnforced = false;
1010
1020
  return true;
1011
1021
  }
1022
+ stopHealthChecks(udid) {
1023
+ for (const ai of this.healthChecks) {
1024
+ if (!udid || ai.udid === udid)
1025
+ this.stopHealthCheck(ai);
1026
+ }
1027
+ }
1012
1028
  async resetLimits() {
1013
1029
  try {
1014
1030
  const mode = this.getCyclingMode();
@@ -1,3 +1,10 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
1
8
  var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2
9
  function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
3
10
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
@@ -25,15 +32,9 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
25
32
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
26
33
  done = true;
27
34
  };
28
- var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
29
- var useValue = arguments.length > 2;
30
- for (var i = 0; i < initializers.length; i++) {
31
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
32
- }
33
- return useValue ? value : void 0;
34
- };
35
35
  import { IncyclistService } from "../../base/service";
36
36
  import { Singleton } from "../../base/types";
37
+ import { Injectable } from "../../base/decorators";
37
38
  import defaultList from './countries.json';
38
39
  import { useIncyclistRoutesApi } from "../../routes/base/api/factory";
39
40
  let Countries = (() => {
@@ -42,16 +43,20 @@ let Countries = (() => {
42
43
  let _classExtraInitializers = [];
43
44
  let _classThis;
44
45
  let _classSuper = IncyclistService;
46
+ let _instanceExtraInitializers = [];
47
+ let _getIncyclistRoutesApi_decorators;
45
48
  var Countries = class extends _classSuper {
46
49
  static { _classThis = this; }
47
50
  static {
48
51
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
52
+ _getIncyclistRoutesApi_decorators = [Injectable];
53
+ __esDecorate(this, null, _getIncyclistRoutesApi_decorators, { kind: "method", name: "getIncyclistRoutesApi", static: false, private: false, access: { has: obj => "getIncyclistRoutesApi" in obj, get: obj => obj.getIncyclistRoutesApi }, metadata: _metadata }, null, _instanceExtraInitializers);
49
54
  __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
50
55
  Countries = _classThis = _classDescriptor.value;
51
56
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
52
57
  __runInitializers(_classThis, _classExtraInitializers);
53
58
  }
54
- language;
59
+ language = __runInitializers(this, _instanceExtraInitializers);
55
60
  countryLists;
56
61
  constructor() {
57
62
  super('Countries');
@@ -85,9 +90,12 @@ let Countries = (() => {
85
90
  return countries.map(c => this.getIsoFromCountry(c, locale));
86
91
  }
87
92
  async getIsoFromLatLng(point) {
88
- const api = useIncyclistRoutesApi().create();
93
+ const api = this.getIncyclistRoutesApi().create();
89
94
  return api.getCountry(point);
90
95
  }
96
+ getIncyclistRoutesApi() {
97
+ return useIncyclistRoutesApi();
98
+ }
91
99
  };
92
100
  return Countries = _classThis;
93
101
  })();
@@ -53,6 +53,11 @@ const verify = (route) => {
53
53
  fixMissingRouteDistances(route.points);
54
54
  }
55
55
  };
56
+ const isNoResponseError = (err) => {
57
+ return err?.message === 'Network Error' ||
58
+ err?.code === 'ERR_NETWORK' ||
59
+ (err?.isAxiosError === true && !err.response);
60
+ };
56
61
  let IncyclistRoutesApi = (() => {
57
62
  let _instanceExtraInitializers = [];
58
63
  let _getUserSettings_decorators;
@@ -168,6 +173,10 @@ let IncyclistRoutesApi = (() => {
168
173
  return res.data.country?.toUpperCase();
169
174
  }
170
175
  catch (err) {
176
+ if (isNoResponseError(err)) {
177
+ this.logger.logEvent({ message: 'getCountry failed: no response from server', reason: err.message });
178
+ return;
179
+ }
171
180
  this.logError(err, 'getCountry');
172
181
  }
173
182
  }
@@ -76,6 +76,7 @@ let FreeRideService = (() => {
76
76
  initialized = false;
77
77
  ivInit;
78
78
  cntInitRetry = 0;
79
+ pendingEnsure;
79
80
  rideSeq = 0;
80
81
  selectedBy = 'auto';
81
82
  startSource = 'default';
@@ -109,6 +110,18 @@ let FreeRideService = (() => {
109
110
  isInitialized() {
110
111
  return this.initialized;
111
112
  }
113
+ async ensureInitialized() {
114
+ if (this.initialized)
115
+ return true;
116
+ if (!this.pendingEnsure) {
117
+ this.logEvent({ message: 'init free ride service on demand' });
118
+ this.pendingEnsure = this.selectStartPosition()
119
+ .catch(err => { this.logError(err, 'ensureInitialized'); })
120
+ .then(() => this.initialized)
121
+ .finally(() => { delete this.pendingEnsure; });
122
+ }
123
+ return this.pendingEnsure;
124
+ }
112
125
  async selectStartPosition(position, opts) {
113
126
  const rideSeq = this.rideSeq;
114
127
  const keepSource = !position && (this.startSource === 'search' || this.startSource === 'map');
@@ -750,6 +750,9 @@ let RouteListService = (() => {
750
750
  isFreeRideSupported() {
751
751
  return this.getFreeRideService().isInitialized();
752
752
  }
753
+ async ensureFreeRideSupported() {
754
+ return await this.getFreeRideService().ensureInitialized();
755
+ }
753
756
  addRoute(route, source = 'system') {
754
757
  const existing = source === 'system' ? this.getRoute(route.description.id) :
755
758
  this.routes.find(r => r.description?.id === route.description.id);
@@ -31,6 +31,11 @@ export declare class ActiveRidesService extends IncyclistService {
31
31
  protected routesStats: ActiveRideCount[];
32
32
  protected routeListSessions: Map<string, Set<string>>;
33
33
  protected isSubscribedRouteListEvents: boolean;
34
+ protected lookupsInFlight: Map<string, Promise<boolean>>;
35
+ protected lookupBackoff: Map<string, {
36
+ until: number;
37
+ delay: number;
38
+ }>;
34
39
  protected readonly activityEventHandlers: {
35
40
  update: any;
36
41
  start: any;
@@ -105,6 +110,12 @@ export declare class ActiveRidesService extends IncyclistService {
105
110
  protected getRemoteActivityDetails(sessionId: string): Promise<ActiveRideEntry>;
106
111
  protected publishUpdateEvent(payload: any): void;
107
112
  protected onActivityUpdateEvent(session: string, payload: ActivityUpdateMessage): Promise<void>;
113
+ protected applyLiveData(entry: ActiveRideEntry, payload: ActivityUpdateMessage): void;
114
+ protected logJoined(prevActive: number, remote: {
115
+ uuid?: string;
116
+ session: string;
117
+ }): void;
118
+ protected lookupRemoteRider(session: string): Promise<boolean>;
108
119
  protected addActiveRide(ride: ActiveRideEntry): void;
109
120
  protected publishStopEvent(): void;
110
121
  protected onActivityStopEvent(session: any, payload: any): void;
@@ -46,6 +46,7 @@ export declare class ActivityListService extends IncyclistService {
46
46
  protected getActivity(id: string): ActivityInfo;
47
47
  protected getListDisplayProperties(): ActivityListDisplayProperties;
48
48
  private getSelectedActivityDisplayProps;
49
+ private refreshExports;
49
50
  protected emitSelected(event: 'loaded' | 'updated'): void;
50
51
  protected emitLists(event: 'loaded' | 'updated'): void;
51
52
  protected getRepo(): ActivitiesRepository;
@@ -13,6 +13,7 @@ export declare class DeviceRideService extends IncyclistService {
13
13
  protected initizialized: boolean;
14
14
  protected adapters: AdapterRideInfo[];
15
15
  protected rideAdapters: AdapterRideInfo[];
16
+ protected healthChecks: Set<AdapterRideInfo>;
16
17
  protected startPromises: Promise<boolean>[];
17
18
  protected data: DeviceData;
18
19
  protected simulatorEnforced: boolean;
@@ -97,6 +98,7 @@ export declare class DeviceRideService extends IncyclistService {
97
98
  cancelStart(): Promise<boolean>;
98
99
  registerOnDataHandler(adapters: AdapterRideInfo[]): void;
99
100
  stop(udid?: string): Promise<boolean>;
101
+ protected stopHealthChecks(udid?: string): void;
100
102
  resetLimits(): Promise<void>;
101
103
  pause(): void;
102
104
  resume(): void;
@@ -13,5 +13,6 @@ export declare class Countries extends IncyclistService {
13
13
  getIsoFromCountry(country: string, locale?: string): string;
14
14
  getIsosFromCountries(countries: Array<string>, locale?: string): Array<string>;
15
15
  getIsoFromLatLng(point: LatLng | Array<LatLng>): Promise<string>;
16
+ protected getIncyclistRoutesApi(): import("../../routes/base/api/factory").IncyclistRoutesApiFactory;
16
17
  }
17
18
  export declare const getCountries: () => Countries;
@@ -12,12 +12,14 @@ export declare class FreeRideService extends IncyclistService {
12
12
  protected initialized: boolean;
13
13
  protected ivInit?: NodeJS.Timeout;
14
14
  protected cntInitRetry: number;
15
+ protected pendingEnsure?: Promise<boolean>;
15
16
  protected rideSeq: number;
16
17
  protected selectedBy: 'auto' | 'user';
17
18
  protected startSource: 'default' | 'last' | 'search' | 'map';
18
19
  constructor();
19
20
  init(): void;
20
21
  isInitialized(): boolean;
22
+ ensureInitialized(): Promise<boolean>;
21
23
  selectStartPosition(position?: LatLng | undefined, opts?: {
22
24
  source?: 'search' | 'map';
23
25
  }): Promise<{
@@ -137,6 +137,7 @@ export declare class RouteListService extends IncyclistService implements IRoute
137
137
  existsBySourceUri(uri: string): boolean;
138
138
  getBySourceUri(uri: string): Route;
139
139
  isFreeRideSupported(): boolean;
140
+ ensureFreeRideSupported(): Promise<boolean>;
140
141
  addRoute(route: Route, source?: 'user' | 'system' | 'import'): void;
141
142
  forgetRoute(target: Route | string): void;
142
143
  createPreview(descr: RouteInfo): Promise<unknown>;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "incyclist-services",
3
- "version": "1.9.13",
3
+ "version": "1.9.15",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },
7
7
  "dependencies": {
8
8
  "@garmin/fitsdk": "^21.218.0",
9
9
  "axios": "^1.21.0",
10
- "incyclist-devices": "^3.0.42",
10
+ "incyclist-devices": "^3.0.43",
11
11
  "promise.any": "^2.0.6",
12
12
  "semver": "^7.7.4",
13
13
  "tcx-builder": "^1.1.1",