incyclist-services 1.9.8 → 1.9.10

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.
@@ -99,6 +99,8 @@ let ActiveRidesService = (() => {
99
99
  isStarted = false;
100
100
  routeListObserver;
101
101
  routesStats = [];
102
+ routeListSessions = new Map();
103
+ isSubscribedRouteListEvents = false;
102
104
  activityEventHandlers = {
103
105
  update: this.onActivityUpdateEvent.bind(this),
104
106
  start: this.onActivityStartEvent.bind(this),
@@ -111,6 +113,7 @@ let ActiveRidesService = (() => {
111
113
  routeList.on('opened', this.onRoutePageOpened.bind(this));
112
114
  routeList.on('closed', () => {
113
115
  delete this.routeListObserver;
116
+ this.unsubscribeRouteListEvents();
114
117
  });
115
118
  }
116
119
  init(session, maxLength = 10) {
@@ -182,7 +185,10 @@ let ActiveRidesService = (() => {
182
185
  }
183
186
  async onRoutePageOpened(observer) {
184
187
  this.routeListObserver = observer;
185
- await this.getActiveRideCounts();
188
+ if (!this.isSubscribedRouteListEvents) {
189
+ await this.getActiveRideCounts();
190
+ this.subscribeRouteListEvents();
191
+ }
186
192
  this.routeListObserver.emit('stats-update', this.routesStats);
187
193
  }
188
194
  async getActiveRideCounts() {
@@ -191,19 +197,17 @@ let ActiveRidesService = (() => {
191
197
  if (!isOnline)
192
198
  return;
193
199
  const activeRides = (await this.getApi().getAll()).filter(ar => ar.ride !== undefined && ar.ride !== null);
194
- const routes = this.getRouteList().getAllRoutes();
195
- const counts = [];
196
- routes.forEach(route => {
197
- const routeRides = activeRides.filter(ar => ar.ride?.routeHash && ar.ride?.routeHash === route.description?.routeHash) ?? [];
198
- const count = routeRides.length;
199
- counts.push({
200
- count,
201
- routeId: route.description.id,
202
- routeHash: route.description.routeHash
203
- });
200
+ this.routeListSessions = new Map();
201
+ activeRides.forEach(ar => {
202
+ const hash = ar.ride?.routeHash;
203
+ if (!hash)
204
+ return;
205
+ if (!this.routeListSessions.has(hash))
206
+ this.routeListSessions.set(hash, new Set());
207
+ this.routeListSessions.get(hash).add(ar.sessionId ?? ar.id);
204
208
  });
205
- this.routesStats = counts;
206
- return counts;
209
+ this.routesStats = this.buildRouteListStats();
210
+ return this.routesStats;
207
211
  }
208
212
  catch (err) {
209
213
  const isOnline = this.getOnlineStatusMonitoring().onlineStatus;
@@ -212,6 +216,73 @@ let ActiveRidesService = (() => {
212
216
  }
213
217
  return [];
214
218
  }
219
+ buildRouteListStats() {
220
+ const routes = this.getRouteList().getAllRoutes();
221
+ return routes.map(route => ({
222
+ count: this.routeListSessions.get(route.description.routeHash)?.size ?? 0,
223
+ routeId: route.description.id,
224
+ routeHash: route.description.routeHash
225
+ }));
226
+ }
227
+ subscribeRouteListEvents() {
228
+ if (this.isSubscribedRouteListEvents)
229
+ return;
230
+ this.getMessageQueue()?.subscribe('incyclist/activity/+/+/+', this.onRouteListActivityEvent.bind(this), 'incyclist/activity');
231
+ this.isSubscribedRouteListEvents = true;
232
+ }
233
+ unsubscribeRouteListEvents() {
234
+ if (!this.isSubscribedRouteListEvents)
235
+ return;
236
+ this.getMessageQueue()?.unsubscribe('incyclist/activity/+/+/+');
237
+ this.isSubscribedRouteListEvents = false;
238
+ }
239
+ onRouteListActivityEvent(topic) {
240
+ const keys = topic.split('/');
241
+ const session = keys[2];
242
+ const routeHash = keys[3];
243
+ const event = keys[4];
244
+ if (!routeHash || !session)
245
+ return;
246
+ if (event === 'start')
247
+ this.addRouteListSession(routeHash, session);
248
+ else if (event === 'stop')
249
+ this.removeRouteListSession(routeHash, session);
250
+ }
251
+ addRouteListSession(routeHash, session) {
252
+ if (!this.routeListSessions.has(routeHash))
253
+ this.routeListSessions.set(routeHash, new Set());
254
+ const sessions = this.routeListSessions.get(routeHash);
255
+ if (sessions.has(session))
256
+ return;
257
+ sessions.add(session);
258
+ this.emitRouteListStatUpdate(routeHash);
259
+ }
260
+ removeRouteListSession(routeHash, session) {
261
+ const sessions = this.routeListSessions.get(routeHash);
262
+ if (!sessions?.has(session))
263
+ return;
264
+ sessions.delete(session);
265
+ this.emitRouteListStatUpdate(routeHash);
266
+ }
267
+ emitRouteListStatUpdate(routeHash) {
268
+ const route = this.getRouteList().getAllRoutes().find(r => r.description.routeHash === routeHash);
269
+ if (!route)
270
+ return;
271
+ const stat = {
272
+ count: this.routeListSessions.get(routeHash)?.size ?? 0,
273
+ routeId: route.description.id,
274
+ routeHash
275
+ };
276
+ const idx = this.routesStats?.findIndex(s => s.routeHash === routeHash) ?? -1;
277
+ if (idx >= 0) {
278
+ this.routesStats[idx] = stat;
279
+ }
280
+ else {
281
+ this.routesStats ??= [];
282
+ this.routesStats.push(stat);
283
+ }
284
+ this.routeListObserver?.emit('stats-update', [stat]);
285
+ }
215
286
  start(session) {
216
287
  if (this.onlineStatusHandler || this.isOnline) {
217
288
  this.initList().catch(err => { this.logError(err, 'start'); });
@@ -600,6 +671,7 @@ let ActiveRidesService = (() => {
600
671
  onDisconnect() {
601
672
  this.getMessageQueue().onDisconnect();
602
673
  this.isSubscribed = false;
674
+ this.isSubscribedRouteListEvents = false;
603
675
  }
604
676
  async onConnect(props) {
605
677
  const { initial = false } = props ?? {};
@@ -607,6 +679,8 @@ let ActiveRidesService = (() => {
607
679
  this.getMessageQueue().onConnect();
608
680
  if (!initial && this.current && !this.isSubscribed)
609
681
  this.subscribeActivityEvents().catch(err => { this.logError(err, 'onConnect'); });
682
+ if (!initial && this.routeListObserver && !this.isSubscribedRouteListEvents)
683
+ this.subscribeRouteListEvents();
610
684
  }
611
685
  async subscribeActivityEvents() {
612
686
  const hash = this.current?.ride.routeHash;
@@ -625,8 +699,11 @@ let ActiveRidesService = (() => {
625
699
  onActivityEvent(topic, payload) {
626
700
  const keys = topic.split('/');
627
701
  const session = keys[2];
702
+ const routeHash = keys[3];
628
703
  if (session === this.current.sessionId)
629
704
  return;
705
+ if (routeHash !== this.current?.ride?.routeHash)
706
+ return;
630
707
  const event = keys[4];
631
708
  const handler = this.activityEventHandlers[event];
632
709
  if (handler)
@@ -290,6 +290,9 @@ function generateQuery(location, radius) {
290
290
  const template = consts_1.GET_WAYS_IN_AREA;
291
291
  return buildQuery(template, boundary);
292
292
  }
293
+ function round7(n) {
294
+ return Math.round(n * 1e7) / 1e7;
295
+ }
293
296
  function boundaryToString(boundary) {
294
297
  if (boundary === undefined)
295
298
  return 'undefined';
@@ -303,7 +306,7 @@ function boundaryToString(boundary) {
303
306
  sw = sw ?? ne;
304
307
  if (sw === undefined)
305
308
  return 'undefined';
306
- return sw.lat + ',' + sw.lng + ',' + ne.lat + ',' + ne.lng;
309
+ return round7(sw.lat) + ',' + round7(sw.lng) + ',' + round7(ne.lat) + ',' + round7(ne.lng);
307
310
  }
308
311
  function pointEquals(p1, p2) {
309
312
  if (p1 === undefined || p2 === undefined)
@@ -542,6 +545,14 @@ function getVector(p1, p2) {
542
545
  const bearing = initialBearingTo(p1, p2);
543
546
  return new utils_1.Vector({ path: { bearing, distance } });
544
547
  }
548
+ function normalizeLongitude(lng) {
549
+ let normalized = lng % 360;
550
+ if (normalized > 180)
551
+ normalized -= 360;
552
+ if (normalized < -180)
553
+ normalized += 360;
554
+ return normalized;
555
+ }
545
556
  function getBounds(lat, lng, offset) {
546
557
  const pi = Math.PI;
547
558
  const m = (1 / ((2 * pi / 360) * consts_1.RADIUS_EARTH)) / 1000;
@@ -550,9 +561,9 @@ function getBounds(lat, lng, offset) {
550
561
  southwest: { lat: undefined, lng: undefined }
551
562
  };
552
563
  boundary.northeast.lat = lat + offset * m;
553
- boundary.northeast.lng = lng + (offset * m) / Math.cos(lat * pi / 180);
564
+ boundary.northeast.lng = normalizeLongitude(lng + (offset * m) / Math.cos(lat * pi / 180));
554
565
  boundary.southwest.lat = lat - offset * m;
555
- boundary.southwest.lng = lng - (offset * m) / Math.cos(lat * pi / 180);
566
+ boundary.southwest.lng = normalizeLongitude(lng - (offset * m) / Math.cos(lat * pi / 180));
556
567
  return boundary;
557
568
  }
558
569
  function isWithinBoundary(location, boundary) {
@@ -143,13 +143,13 @@ let RoutesApiLoader = (() => {
143
143
  await this.processRouteFromApi(p.value[j], loadDetailRequired);
144
144
  }
145
145
  }
146
- this.loadObserver.emit('loaded');
146
+ this.loadObserver?.emit('loaded');
147
147
  if (loadDetailRequired.length > 0) {
148
148
  await this.loadDetails(loadDetailRequired, true);
149
149
  }
150
- this.loadObserver.emit('done');
150
+ this.loadObserver?.emit('done');
151
151
  await (0, sleep_1.sleep)(1);
152
- this.loadObserver.stop();
152
+ this.loadObserver?.stop();
153
153
  delete this.loadObserver;
154
154
  }
155
155
  async processRouteFromApi(descr, items) {
@@ -46,6 +46,8 @@ const OVERPASS_URL_PRIMARY = 'https://overpass-api.de/api/interpreter';
46
46
  const OVERPASS_URL_ALT2 = 'https://lz4.overpass-api.de/api/interpreter';
47
47
  const OVERPASS_URL_ALT3 = 'https://maps.mail.ru/osm/tools/overpass/api/interpreter';
48
48
  exports.OVERPASS_URL_DEFAULT = OVERPASS_URL_PRIMARY;
49
+ const OVERPASS_SELF_HOSTED_URL_DEFAULT = 'https://overpass.incyclist.com/api/v1/interpreter';
50
+ const SELF_HOSTED_MAX_TIMEOUT_MS = 5000;
49
51
  const DEFAULT_MIRRORS = [OVERPASS_URL_PRIMARY, OVERPASS_URL_ALT2, OVERPASS_URL_ALT3];
50
52
  let OverpassApi = (() => {
51
53
  let _classDecorators = [types_1.Singleton];
@@ -72,9 +74,10 @@ let OverpassApi = (() => {
72
74
  url = __runInitializers(this, _instanceExtraInitializers);
73
75
  mirrors = [];
74
76
  logger;
77
+ restClient;
75
78
  constructor(props) {
76
79
  super();
77
- this.mirrors = DEFAULT_MIRRORS;
80
+ this.mirrors = [...DEFAULT_MIRRORS];
78
81
  this.url = props?.url ?? this.mirrors[0];
79
82
  this.logger = new gd_eventlog_1.EventLogger('Overpass');
80
83
  if (props?.url) {
@@ -170,11 +173,75 @@ let OverpassApi = (() => {
170
173
  }
171
174
  async query(queryOL, timeout) {
172
175
  const ts = Date.now();
173
- this.logger.logEvent({ message: 'query', queryOL, queryId: ts, timeout });
174
- const res = await this.bulkQuery(queryOL, timeout);
175
- this.logger.logEvent({ message: 'query result', queryId: ts, hasData: res !== undefined, duration: Date.now() - ts });
176
+ const queryId = ts;
177
+ this.logger.logEvent({ message: 'query', queryOL, queryId, timeout });
178
+ const hasOverallTimeout = timeout !== undefined && timeout !== null;
179
+ const selfHostedTimeout = hasOverallTimeout ? Math.min(timeout / 2, SELF_HOSTED_MAX_TIMEOUT_MS) : SELF_HOSTED_MAX_TIMEOUT_MS;
180
+ const selfHosted = await this.trySelfHosted(queryOL, queryId, selfHostedTimeout);
181
+ if (selfHosted.ok) {
182
+ this.logger.logEvent({ message: 'query result', queryId, hasData: true, duration: Date.now() - ts, source: 'self-hosted', fallback: false, cache: selfHosted.cache });
183
+ return selfHosted.data;
184
+ }
185
+ const remaining = hasOverallTimeout ? Math.max(timeout - (Date.now() - ts), 0) : undefined;
186
+ const res = await this.bulkQuery(queryOL, remaining);
187
+ this.logger.logEvent({ message: 'query result', queryId, hasData: res !== undefined, duration: Date.now() - ts, source: res !== undefined ? 'public' : 'none', fallback: true, cache: 'n/a' });
176
188
  return res;
177
189
  }
190
+ async trySelfHosted(queryOL, queryId, timeoutMs) {
191
+ const ts = Date.now();
192
+ const url = this.getSelfHostedUrl();
193
+ try {
194
+ const outcome = await Promise.race([
195
+ this.getRestClient().post(url, queryOL, { headers: { 'Content-Type': 'text/plain' }, validateStatus: () => true }),
196
+ (0, sleep_1.sleep)(timeoutMs).then(() => 'timeout')
197
+ ]);
198
+ if (outcome === 'timeout') {
199
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'timeout', duration: Date.now() - ts });
200
+ return { ok: false };
201
+ }
202
+ if (outcome.status >= 400) {
203
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'http', httpStatus: outcome.status, duration: Date.now() - ts });
204
+ return { ok: false };
205
+ }
206
+ if (!this.isValidOverpassBody(outcome.data)) {
207
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'invalid-body', duration: Date.now() - ts });
208
+ return { ok: false };
209
+ }
210
+ return { ok: true, data: outcome.data, cache: this.extractCacheHeader(outcome) };
211
+ }
212
+ catch {
213
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'network', duration: Date.now() - ts });
214
+ return { ok: false };
215
+ }
216
+ }
217
+ isValidOverpassBody(data) {
218
+ if (data === undefined || data === null)
219
+ return false;
220
+ if (typeof data === 'string')
221
+ return data.trim().length > 0;
222
+ return true;
223
+ }
224
+ extractCacheHeader(res) {
225
+ const headers = res.headers;
226
+ if (!headers)
227
+ return 'n/a';
228
+ const value = headers['x-cache'] ?? headers['X-Cache'];
229
+ return typeof value === 'string' ? value : 'n/a';
230
+ }
231
+ getSelfHostedUrl() {
232
+ try {
233
+ return this.getUserSettings().get('OVERPASS_API', OVERPASS_SELF_HOSTED_URL_DEFAULT);
234
+ }
235
+ catch {
236
+ return OVERPASS_SELF_HOSTED_URL_DEFAULT;
237
+ }
238
+ }
239
+ getRestClient() {
240
+ if (!this.restClient) {
241
+ this.restClient = api_1.IncyclistRestApiClient.getClient();
242
+ }
243
+ return this.restClient;
244
+ }
178
245
  async singleQuery(queryOL) {
179
246
  const res = await this.post(this.url, queryOL);
180
247
  return res.data;
@@ -282,7 +349,7 @@ let OverpassApi = (() => {
282
349
  throw lastError;
283
350
  }
284
351
  reset() {
285
- this.mirrors = DEFAULT_MIRRORS;
352
+ this.mirrors = [...DEFAULT_MIRRORS];
286
353
  this.url = this.mirrors[0];
287
354
  }
288
355
  getAppVersion() {
@@ -488,6 +488,7 @@ let UserInterfaceServcie = (() => {
488
488
  const freeRide = (0, routes_1.useFreeRideService)();
489
489
  const workouts = (0, workouts_1.useWorkoutList)();
490
490
  const activities = (0, activities_1.useActivityList)();
491
+ (0, activities_1.useActiveRides)();
491
492
  const promises = [
492
493
  routes.preload().wait(),
493
494
  freeRide.init(),
@@ -96,6 +96,8 @@ let ActiveRidesService = (() => {
96
96
  isStarted = false;
97
97
  routeListObserver;
98
98
  routesStats = [];
99
+ routeListSessions = new Map();
100
+ isSubscribedRouteListEvents = false;
99
101
  activityEventHandlers = {
100
102
  update: this.onActivityUpdateEvent.bind(this),
101
103
  start: this.onActivityStartEvent.bind(this),
@@ -108,6 +110,7 @@ let ActiveRidesService = (() => {
108
110
  routeList.on('opened', this.onRoutePageOpened.bind(this));
109
111
  routeList.on('closed', () => {
110
112
  delete this.routeListObserver;
113
+ this.unsubscribeRouteListEvents();
111
114
  });
112
115
  }
113
116
  init(session, maxLength = 10) {
@@ -179,7 +182,10 @@ let ActiveRidesService = (() => {
179
182
  }
180
183
  async onRoutePageOpened(observer) {
181
184
  this.routeListObserver = observer;
182
- await this.getActiveRideCounts();
185
+ if (!this.isSubscribedRouteListEvents) {
186
+ await this.getActiveRideCounts();
187
+ this.subscribeRouteListEvents();
188
+ }
183
189
  this.routeListObserver.emit('stats-update', this.routesStats);
184
190
  }
185
191
  async getActiveRideCounts() {
@@ -188,19 +194,17 @@ let ActiveRidesService = (() => {
188
194
  if (!isOnline)
189
195
  return;
190
196
  const activeRides = (await this.getApi().getAll()).filter(ar => ar.ride !== undefined && ar.ride !== null);
191
- const routes = this.getRouteList().getAllRoutes();
192
- const counts = [];
193
- routes.forEach(route => {
194
- const routeRides = activeRides.filter(ar => ar.ride?.routeHash && ar.ride?.routeHash === route.description?.routeHash) ?? [];
195
- const count = routeRides.length;
196
- counts.push({
197
- count,
198
- routeId: route.description.id,
199
- routeHash: route.description.routeHash
200
- });
197
+ this.routeListSessions = new Map();
198
+ activeRides.forEach(ar => {
199
+ const hash = ar.ride?.routeHash;
200
+ if (!hash)
201
+ return;
202
+ if (!this.routeListSessions.has(hash))
203
+ this.routeListSessions.set(hash, new Set());
204
+ this.routeListSessions.get(hash).add(ar.sessionId ?? ar.id);
201
205
  });
202
- this.routesStats = counts;
203
- return counts;
206
+ this.routesStats = this.buildRouteListStats();
207
+ return this.routesStats;
204
208
  }
205
209
  catch (err) {
206
210
  const isOnline = this.getOnlineStatusMonitoring().onlineStatus;
@@ -209,6 +213,73 @@ let ActiveRidesService = (() => {
209
213
  }
210
214
  return [];
211
215
  }
216
+ buildRouteListStats() {
217
+ const routes = this.getRouteList().getAllRoutes();
218
+ return routes.map(route => ({
219
+ count: this.routeListSessions.get(route.description.routeHash)?.size ?? 0,
220
+ routeId: route.description.id,
221
+ routeHash: route.description.routeHash
222
+ }));
223
+ }
224
+ subscribeRouteListEvents() {
225
+ if (this.isSubscribedRouteListEvents)
226
+ return;
227
+ this.getMessageQueue()?.subscribe('incyclist/activity/+/+/+', this.onRouteListActivityEvent.bind(this), 'incyclist/activity');
228
+ this.isSubscribedRouteListEvents = true;
229
+ }
230
+ unsubscribeRouteListEvents() {
231
+ if (!this.isSubscribedRouteListEvents)
232
+ return;
233
+ this.getMessageQueue()?.unsubscribe('incyclist/activity/+/+/+');
234
+ this.isSubscribedRouteListEvents = false;
235
+ }
236
+ onRouteListActivityEvent(topic) {
237
+ const keys = topic.split('/');
238
+ const session = keys[2];
239
+ const routeHash = keys[3];
240
+ const event = keys[4];
241
+ if (!routeHash || !session)
242
+ return;
243
+ if (event === 'start')
244
+ this.addRouteListSession(routeHash, session);
245
+ else if (event === 'stop')
246
+ this.removeRouteListSession(routeHash, session);
247
+ }
248
+ addRouteListSession(routeHash, session) {
249
+ if (!this.routeListSessions.has(routeHash))
250
+ this.routeListSessions.set(routeHash, new Set());
251
+ const sessions = this.routeListSessions.get(routeHash);
252
+ if (sessions.has(session))
253
+ return;
254
+ sessions.add(session);
255
+ this.emitRouteListStatUpdate(routeHash);
256
+ }
257
+ removeRouteListSession(routeHash, session) {
258
+ const sessions = this.routeListSessions.get(routeHash);
259
+ if (!sessions?.has(session))
260
+ return;
261
+ sessions.delete(session);
262
+ this.emitRouteListStatUpdate(routeHash);
263
+ }
264
+ emitRouteListStatUpdate(routeHash) {
265
+ const route = this.getRouteList().getAllRoutes().find(r => r.description.routeHash === routeHash);
266
+ if (!route)
267
+ return;
268
+ const stat = {
269
+ count: this.routeListSessions.get(routeHash)?.size ?? 0,
270
+ routeId: route.description.id,
271
+ routeHash
272
+ };
273
+ const idx = this.routesStats?.findIndex(s => s.routeHash === routeHash) ?? -1;
274
+ if (idx >= 0) {
275
+ this.routesStats[idx] = stat;
276
+ }
277
+ else {
278
+ this.routesStats ??= [];
279
+ this.routesStats.push(stat);
280
+ }
281
+ this.routeListObserver?.emit('stats-update', [stat]);
282
+ }
212
283
  start(session) {
213
284
  if (this.onlineStatusHandler || this.isOnline) {
214
285
  this.initList().catch(err => { this.logError(err, 'start'); });
@@ -597,6 +668,7 @@ let ActiveRidesService = (() => {
597
668
  onDisconnect() {
598
669
  this.getMessageQueue().onDisconnect();
599
670
  this.isSubscribed = false;
671
+ this.isSubscribedRouteListEvents = false;
600
672
  }
601
673
  async onConnect(props) {
602
674
  const { initial = false } = props ?? {};
@@ -604,6 +676,8 @@ let ActiveRidesService = (() => {
604
676
  this.getMessageQueue().onConnect();
605
677
  if (!initial && this.current && !this.isSubscribed)
606
678
  this.subscribeActivityEvents().catch(err => { this.logError(err, 'onConnect'); });
679
+ if (!initial && this.routeListObserver && !this.isSubscribedRouteListEvents)
680
+ this.subscribeRouteListEvents();
607
681
  }
608
682
  async subscribeActivityEvents() {
609
683
  const hash = this.current?.ride.routeHash;
@@ -622,8 +696,11 @@ let ActiveRidesService = (() => {
622
696
  onActivityEvent(topic, payload) {
623
697
  const keys = topic.split('/');
624
698
  const session = keys[2];
699
+ const routeHash = keys[3];
625
700
  if (session === this.current.sessionId)
626
701
  return;
702
+ if (routeHash !== this.current?.ride?.routeHash)
703
+ return;
627
704
  const event = keys[4];
628
705
  const handler = this.activityEventHandlers[event];
629
706
  if (handler)
@@ -254,6 +254,9 @@ export function generateQuery(location, radius) {
254
254
  const template = GET_WAYS_IN_AREA;
255
255
  return buildQuery(template, boundary);
256
256
  }
257
+ function round7(n) {
258
+ return Math.round(n * 1e7) / 1e7;
259
+ }
257
260
  export function boundaryToString(boundary) {
258
261
  if (boundary === undefined)
259
262
  return 'undefined';
@@ -267,7 +270,7 @@ export function boundaryToString(boundary) {
267
270
  sw = sw ?? ne;
268
271
  if (sw === undefined)
269
272
  return 'undefined';
270
- return sw.lat + ',' + sw.lng + ',' + ne.lat + ',' + ne.lng;
273
+ return round7(sw.lat) + ',' + round7(sw.lng) + ',' + round7(ne.lat) + ',' + round7(ne.lng);
271
274
  }
272
275
  export function pointEquals(p1, p2) {
273
276
  if (p1 === undefined || p2 === undefined)
@@ -506,6 +509,14 @@ export function getVector(p1, p2) {
506
509
  const bearing = initialBearingTo(p1, p2);
507
510
  return new Vector({ path: { bearing, distance } });
508
511
  }
512
+ function normalizeLongitude(lng) {
513
+ let normalized = lng % 360;
514
+ if (normalized > 180)
515
+ normalized -= 360;
516
+ if (normalized < -180)
517
+ normalized += 360;
518
+ return normalized;
519
+ }
509
520
  export function getBounds(lat, lng, offset) {
510
521
  const pi = Math.PI;
511
522
  const m = (1 / ((2 * pi / 360) * RADIUS_EARTH)) / 1000;
@@ -514,9 +525,9 @@ export function getBounds(lat, lng, offset) {
514
525
  southwest: { lat: undefined, lng: undefined }
515
526
  };
516
527
  boundary.northeast.lat = lat + offset * m;
517
- boundary.northeast.lng = lng + (offset * m) / Math.cos(lat * pi / 180);
528
+ boundary.northeast.lng = normalizeLongitude(lng + (offset * m) / Math.cos(lat * pi / 180));
518
529
  boundary.southwest.lat = lat - offset * m;
519
- boundary.southwest.lng = lng - (offset * m) / Math.cos(lat * pi / 180);
530
+ boundary.southwest.lng = normalizeLongitude(lng - (offset * m) / Math.cos(lat * pi / 180));
520
531
  return boundary;
521
532
  }
522
533
  export function isWithinBoundary(location, boundary) {
@@ -140,13 +140,13 @@ let RoutesApiLoader = (() => {
140
140
  await this.processRouteFromApi(p.value[j], loadDetailRequired);
141
141
  }
142
142
  }
143
- this.loadObserver.emit('loaded');
143
+ this.loadObserver?.emit('loaded');
144
144
  if (loadDetailRequired.length > 0) {
145
145
  await this.loadDetails(loadDetailRequired, true);
146
146
  }
147
- this.loadObserver.emit('done');
147
+ this.loadObserver?.emit('done');
148
148
  await sleep(1);
149
- this.loadObserver.stop();
149
+ this.loadObserver?.stop();
150
150
  delete this.loadObserver;
151
151
  }
152
152
  async processRouteFromApi(descr, items) {
@@ -37,12 +37,14 @@ import { sleep } from '../../utils/sleep';
37
37
  import { AppApiBase } from '../../apps/base/api/base';
38
38
  import { EventLogger } from 'gd-eventlog';
39
39
  import { Injectable } from '../../base/decorators';
40
- import { getBindings } from '../../api';
40
+ import { getBindings, IncyclistRestApiClient } from '../../api';
41
41
  import { useUserSettings } from '../../settings';
42
42
  const OVERPASS_URL_PRIMARY = 'https://overpass-api.de/api/interpreter';
43
43
  const OVERPASS_URL_ALT2 = 'https://lz4.overpass-api.de/api/interpreter';
44
44
  const OVERPASS_URL_ALT3 = 'https://maps.mail.ru/osm/tools/overpass/api/interpreter';
45
45
  export const OVERPASS_URL_DEFAULT = OVERPASS_URL_PRIMARY;
46
+ const OVERPASS_SELF_HOSTED_URL_DEFAULT = 'https://overpass.incyclist.com/api/v1/interpreter';
47
+ const SELF_HOSTED_MAX_TIMEOUT_MS = 5000;
46
48
  const DEFAULT_MIRRORS = [OVERPASS_URL_PRIMARY, OVERPASS_URL_ALT2, OVERPASS_URL_ALT3];
47
49
  let OverpassApi = (() => {
48
50
  let _classDecorators = [Singleton];
@@ -69,9 +71,10 @@ let OverpassApi = (() => {
69
71
  url = __runInitializers(this, _instanceExtraInitializers);
70
72
  mirrors = [];
71
73
  logger;
74
+ restClient;
72
75
  constructor(props) {
73
76
  super();
74
- this.mirrors = DEFAULT_MIRRORS;
77
+ this.mirrors = [...DEFAULT_MIRRORS];
75
78
  this.url = props?.url ?? this.mirrors[0];
76
79
  this.logger = new EventLogger('Overpass');
77
80
  if (props?.url) {
@@ -167,11 +170,75 @@ let OverpassApi = (() => {
167
170
  }
168
171
  async query(queryOL, timeout) {
169
172
  const ts = Date.now();
170
- this.logger.logEvent({ message: 'query', queryOL, queryId: ts, timeout });
171
- const res = await this.bulkQuery(queryOL, timeout);
172
- this.logger.logEvent({ message: 'query result', queryId: ts, hasData: res !== undefined, duration: Date.now() - ts });
173
+ const queryId = ts;
174
+ this.logger.logEvent({ message: 'query', queryOL, queryId, timeout });
175
+ const hasOverallTimeout = timeout !== undefined && timeout !== null;
176
+ const selfHostedTimeout = hasOverallTimeout ? Math.min(timeout / 2, SELF_HOSTED_MAX_TIMEOUT_MS) : SELF_HOSTED_MAX_TIMEOUT_MS;
177
+ const selfHosted = await this.trySelfHosted(queryOL, queryId, selfHostedTimeout);
178
+ if (selfHosted.ok) {
179
+ this.logger.logEvent({ message: 'query result', queryId, hasData: true, duration: Date.now() - ts, source: 'self-hosted', fallback: false, cache: selfHosted.cache });
180
+ return selfHosted.data;
181
+ }
182
+ const remaining = hasOverallTimeout ? Math.max(timeout - (Date.now() - ts), 0) : undefined;
183
+ const res = await this.bulkQuery(queryOL, remaining);
184
+ this.logger.logEvent({ message: 'query result', queryId, hasData: res !== undefined, duration: Date.now() - ts, source: res !== undefined ? 'public' : 'none', fallback: true, cache: 'n/a' });
173
185
  return res;
174
186
  }
187
+ async trySelfHosted(queryOL, queryId, timeoutMs) {
188
+ const ts = Date.now();
189
+ const url = this.getSelfHostedUrl();
190
+ try {
191
+ const outcome = await Promise.race([
192
+ this.getRestClient().post(url, queryOL, { headers: { 'Content-Type': 'text/plain' }, validateStatus: () => true }),
193
+ sleep(timeoutMs).then(() => 'timeout')
194
+ ]);
195
+ if (outcome === 'timeout') {
196
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'timeout', duration: Date.now() - ts });
197
+ return { ok: false };
198
+ }
199
+ if (outcome.status >= 400) {
200
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'http', httpStatus: outcome.status, duration: Date.now() - ts });
201
+ return { ok: false };
202
+ }
203
+ if (!this.isValidOverpassBody(outcome.data)) {
204
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'invalid-body', duration: Date.now() - ts });
205
+ return { ok: false };
206
+ }
207
+ return { ok: true, data: outcome.data, cache: this.extractCacheHeader(outcome) };
208
+ }
209
+ catch {
210
+ this.logger.logEvent({ message: 'self-hosted failed', queryId, reason: 'network', duration: Date.now() - ts });
211
+ return { ok: false };
212
+ }
213
+ }
214
+ isValidOverpassBody(data) {
215
+ if (data === undefined || data === null)
216
+ return false;
217
+ if (typeof data === 'string')
218
+ return data.trim().length > 0;
219
+ return true;
220
+ }
221
+ extractCacheHeader(res) {
222
+ const headers = res.headers;
223
+ if (!headers)
224
+ return 'n/a';
225
+ const value = headers['x-cache'] ?? headers['X-Cache'];
226
+ return typeof value === 'string' ? value : 'n/a';
227
+ }
228
+ getSelfHostedUrl() {
229
+ try {
230
+ return this.getUserSettings().get('OVERPASS_API', OVERPASS_SELF_HOSTED_URL_DEFAULT);
231
+ }
232
+ catch {
233
+ return OVERPASS_SELF_HOSTED_URL_DEFAULT;
234
+ }
235
+ }
236
+ getRestClient() {
237
+ if (!this.restClient) {
238
+ this.restClient = IncyclistRestApiClient.getClient();
239
+ }
240
+ return this.restClient;
241
+ }
175
242
  async singleQuery(queryOL) {
176
243
  const res = await this.post(this.url, queryOL);
177
244
  return res.data;
@@ -279,7 +346,7 @@ let OverpassApi = (() => {
279
346
  throw lastError;
280
347
  }
281
348
  reset() {
282
- this.mirrors = DEFAULT_MIRRORS;
349
+ this.mirrors = [...DEFAULT_MIRRORS];
283
350
  this.url = this.mirrors[0];
284
351
  }
285
352
  getAppVersion() {
@@ -45,7 +45,7 @@ import { useDevicePairing } from "../devices/pairing";
45
45
  import { initPairingVisitTracker, usePairingVisitTracker } from "../devices/page/base/visit-log-factory";
46
46
  import { useFreeRideService, useRouteList } from "../routes";
47
47
  import { useWorkoutList } from "../workouts";
48
- import { useActivityList } from "../activities";
48
+ import { useActiveRides, useActivityList } from "../activities";
49
49
  import { useOnlineStatusMonitoring } from "../monitoring";
50
50
  import { useAppState, useFeatureToggleSync } from "../appstate";
51
51
  import { IncyclistPageService } from "../base/pages";
@@ -485,6 +485,7 @@ let UserInterfaceServcie = (() => {
485
485
  const freeRide = useFreeRideService();
486
486
  const workouts = useWorkoutList();
487
487
  const activities = useActivityList();
488
+ useActiveRides();
488
489
  const promises = [
489
490
  routes.preload().wait(),
490
491
  freeRide.init(),
@@ -29,6 +29,8 @@ export declare class ActiveRidesService extends IncyclistService {
29
29
  protected isStarted: boolean;
30
30
  protected routeListObserver: Observer;
31
31
  protected routesStats: ActiveRideCount[];
32
+ protected routeListSessions: Map<string, Set<string>>;
33
+ protected isSubscribedRouteListEvents: boolean;
32
34
  protected readonly activityEventHandlers: {
33
35
  update: any;
34
36
  start: any;
@@ -43,6 +45,13 @@ export declare class ActiveRidesService extends IncyclistService {
43
45
  protected countRidesByRoute(): Map<string, number>;
44
46
  protected onRoutePageOpened(observer: Observer): Promise<void>;
45
47
  protected getActiveRideCounts(): Promise<ActiveRideCount[]>;
48
+ protected buildRouteListStats(): ActiveRideCount[];
49
+ protected subscribeRouteListEvents(): void;
50
+ protected unsubscribeRouteListEvents(): void;
51
+ protected onRouteListActivityEvent(topic: string): void;
52
+ protected addRouteListSession(routeHash: string, session: string): void;
53
+ protected removeRouteListSession(routeHash: string, session: string): void;
54
+ protected emitRouteListStatUpdate(routeHash: string): void;
46
55
  protected start(session: string): void;
47
56
  protected initList(): Promise<void>;
48
57
  protected onActivityUpdated(): void;
@@ -1,13 +1,14 @@
1
1
  import { AppApiBase } from '../../apps/base/api/base';
2
2
  import { EventLogger } from 'gd-eventlog';
3
3
  import { UserSettingsService } from '../../settings';
4
- import { AxiosResponse } from 'axios';
4
+ import { AxiosInstance, AxiosResponse } from 'axios';
5
5
  import type { IFetchBinding } from '../../api/fetch/types';
6
6
  export declare const OVERPASS_URL_DEFAULT = "https://overpass-api.de/api/interpreter";
7
7
  export declare class OverpassApi extends AppApiBase {
8
8
  protected url: string;
9
9
  protected mirrors: string[];
10
10
  protected logger: EventLogger;
11
+ protected restClient: AxiosInstance;
11
12
  constructor(props?: {
12
13
  url: string;
13
14
  });
@@ -19,6 +20,15 @@ export declare class OverpassApi extends AppApiBase {
19
20
  protected postViaFetchBinding(fetchBinding: IFetchBinding, url: string, data?: object | string): Promise<AxiosResponse>;
20
21
  protected postViaNodeHttps(https: any, url: string, data?: object | string): Promise<any>;
21
22
  query(queryOL: string, timeout?: number): Promise<JSON | string | undefined>;
23
+ protected trySelfHosted(queryOL: string, queryId: number, timeoutMs: number): Promise<{
24
+ ok: boolean;
25
+ data?: JSON | string;
26
+ cache?: string;
27
+ }>;
28
+ protected isValidOverpassBody(data: JSON | string | undefined | null): boolean;
29
+ protected extractCacheHeader(res: AxiosResponse): string;
30
+ protected getSelfHostedUrl(): string;
31
+ protected getRestClient(): AxiosInstance;
22
32
  singleQuery(queryOL: string): Promise<JSON | string>;
23
33
  rotateUrl(): void;
24
34
  protected getBaseUrl(): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incyclist-services",
3
- "version": "1.9.8",
3
+ "version": "1.9.10",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },
@@ -19,18 +19,18 @@
19
19
  "@serialport/binding-mock": "^10.2.2",
20
20
  "@serialport/bindings-interface": "^1.2.2",
21
21
  "@types/jest": "^30.0.0",
22
- "@types/node": "^26.6.4",
23
- "@typescript-eslint/eslint-plugin": "^8.70.1",
22
+ "@types/node": "^26.6.6",
23
+ "@typescript-eslint/eslint-plugin": "^8.72.1",
24
24
  "@typescript-eslint/parser": "^8.71.0",
25
25
  "dotenv": "^17.4.2",
26
- "eslint": "^10.9.1",
26
+ "eslint": "^10.12.0",
27
27
  "formdata-node": "^6.0.3",
28
- "globals": "^17.12.0",
28
+ "globals": "^17.13.0",
29
29
  "jest": "^30.5.2",
30
30
  "jsdoc": "^4.0.5",
31
31
  "ts-jest": "^29.4.12",
32
32
  "typedoc": "^0.28.20",
33
- "typedoc-plugin-markdown": "^4.12.0",
33
+ "typedoc-plugin-markdown": "^4.13.1",
34
34
  "typedoc-plugin-no-inherit": "^1.6.1",
35
35
  "typescript": "^5.9.3",
36
36
  "typescript-eslint": "^8.67.0"