incyclist-services 1.9.7 → 1.9.8

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.
Files changed (55) hide show
  1. package/lib/cjs/api/rest/api.js +7 -3
  2. package/lib/cjs/api/rest/external.js +26 -0
  3. package/lib/cjs/apps/googleMaps/service.js +2 -0
  4. package/lib/cjs/apps/service.js +4 -1
  5. package/lib/cjs/devices/pairing/service.js +0 -1
  6. package/lib/cjs/i18n/countries/service.js +2 -2
  7. package/lib/cjs/routes/base/api/api.js +196 -0
  8. package/lib/cjs/routes/base/api/factory.js +93 -0
  9. package/lib/cjs/routes/base/api/index.js +14 -184
  10. package/lib/cjs/routes/base/parsers/tacx/TacxParser.js +1 -1
  11. package/lib/cjs/routes/free-ride/service.js +41 -0
  12. package/lib/cjs/routes/list/loaders/DBLoader.js +0 -1
  13. package/lib/cjs/routes/list/loaders/api.js +270 -176
  14. package/lib/cjs/routes/list/service.js +401 -357
  15. package/lib/cjs/ui/service.js +1 -2
  16. package/lib/cjs/utils/string.js +21 -1
  17. package/lib/esm/api/rest/api.js +7 -3
  18. package/lib/esm/api/rest/external.js +22 -0
  19. package/lib/esm/api/rest/incyclist copy.js +33 -0
  20. package/lib/esm/apps/googleMaps/service.js +2 -0
  21. package/lib/esm/apps/service.js +4 -1
  22. package/lib/esm/devices/configuration/model/add/index.js +1 -0
  23. package/lib/esm/devices/configuration/model/exclusion/index.js +1 -0
  24. package/lib/esm/devices/pairing/capability.js +1 -0
  25. package/lib/esm/devices/pairing/service.js +0 -1
  26. package/lib/esm/i18n/countries/service.js +2 -2
  27. package/lib/esm/routes/base/api/api.js +194 -0
  28. package/lib/esm/routes/base/api/factory.js +86 -0
  29. package/lib/esm/routes/base/api/index.js +2 -186
  30. package/lib/esm/routes/base/parsers/tacx/TacxParser.js +1 -1
  31. package/lib/esm/routes/free-ride/service.js +41 -0
  32. package/lib/esm/routes/list/loaders/DBLoader.js +0 -1
  33. package/lib/esm/routes/list/loaders/api.js +272 -174
  34. package/lib/esm/routes/list/service.js +401 -357
  35. package/lib/esm/ui/service.js +2 -3
  36. package/lib/esm/utils/string.js +18 -0
  37. package/lib/types/api/rest/api.d.ts +2 -2
  38. package/lib/types/api/rest/external.d.ts +7 -0
  39. package/lib/types/api/rest/incyclist copy.d.ts +7 -0
  40. package/lib/types/api/rest/types.d.ts +5 -3
  41. package/lib/types/apps/service.d.ts +1 -0
  42. package/lib/types/devices/configuration/model/add/index.d.ts +10 -0
  43. package/lib/types/devices/configuration/model/exclusion/index.d.ts +19 -0
  44. package/lib/types/devices/pairing/capability.d.ts +10 -0
  45. package/lib/types/routes/base/api/api.d.ts +23 -0
  46. package/lib/types/routes/base/api/factory.d.ts +7 -0
  47. package/lib/types/routes/base/api/index.d.ts +2 -26
  48. package/lib/types/routes/base/api/types.d.ts +10 -0
  49. package/lib/types/routes/base/parsers/tacx/TacxParser.d.ts +1 -1
  50. package/lib/types/routes/base/types/index.d.ts +1 -0
  51. package/lib/types/routes/free-ride/service.d.ts +6 -0
  52. package/lib/types/routes/list/loaders/api.d.ts +6 -3
  53. package/lib/types/routes/list/service.d.ts +37 -29
  54. package/lib/types/utils/string.d.ts +2 -0
  55. package/package.json +1 -1
@@ -42,6 +42,8 @@ import { useUserSettings } from "../../settings";
42
42
  import { distanceBetween, calculateHeaderFromPoints as getHeadingBetween } from "../../utils/geo";
43
43
  import { waitNextTick } from "../../utils";
44
44
  import clone from "../../utils/clone";
45
+ const INIT_RETRY = 15 * 1000;
46
+ const MAX_RETRIES = 1;
45
47
  let FreeRideService = (() => {
46
48
  let _classDecorators = [Singleton];
47
49
  let _classDescriptor;
@@ -70,13 +72,43 @@ let FreeRideService = (() => {
70
72
  options;
71
73
  currentSegment;
72
74
  lastOptionsQueryValid = true;
75
+ initialized = false;
76
+ ivInit;
77
+ cntInitRetry = 0;
73
78
  constructor() {
74
79
  super('FreeRide');
75
80
  this.options = [];
76
81
  }
82
+ init() {
83
+ this.logEvent({ message: 'init free ride service' });
84
+ this.selectStartPosition()
85
+ .catch(err => {
86
+ this.logError(err, 'init');
87
+ })
88
+ .finally(() => {
89
+ this.logEvent({ message: 'init free ride service result', success: this.initialized });
90
+ this.ivInit = setInterval(() => {
91
+ if (this.cntInitRetry < MAX_RETRIES) {
92
+ this.cntInitRetry++;
93
+ this.logEvent({ message: 'init free ride service retry' });
94
+ this.selectStartPosition().catch(err => { this.logError(err, 'init'); });
95
+ }
96
+ else {
97
+ clearInterval(this.ivInit);
98
+ delete this.ivInit;
99
+ }
100
+ }, INIT_RETRY);
101
+ });
102
+ }
103
+ isInitialized() {
104
+ return this.initialized;
105
+ }
77
106
  async selectStartPosition(position) {
78
107
  this.setStartPosition(position);
79
108
  const map = await this.getMapArea().load(this.startPosition);
109
+ if (!this.initialized && map) {
110
+ this.setInitialized();
111
+ }
80
112
  await this.getStartOptions(map);
81
113
  return this.getRouteDefinitionDisplayProps();
82
114
  }
@@ -127,6 +159,15 @@ let FreeRideService = (() => {
127
159
  this.emit('segment-update', segment);
128
160
  this.logEvent({ message: 'current segment changed', segment: this.buildId(this.selectedOption) });
129
161
  }
162
+ setInitialized() {
163
+ this.initialized = true;
164
+ if (this.ivInit) {
165
+ clearInterval(this.ivInit);
166
+ delete this.ivInit;
167
+ this.logEvent({ message: 'init free ride service success' });
168
+ }
169
+ this.emit('initialized');
170
+ }
130
171
  getOption(option) {
131
172
  return (this.options ?? []).find(o => o.ui?.id === option.id);
132
173
  }
@@ -3,7 +3,6 @@ import { JsonRepository } from "../../../api";
3
3
  import { Observer } from "../../../base/types/observer";
4
4
  import { Route } from "../../base/model/route";
5
5
  import { Loader } from "./types";
6
- const DETAILS_PRELOAD_CNT = 20;
7
6
  export class DBLoader extends Loader {
8
7
  routeDescriptions;
9
8
  videosRepo;
@@ -1,12 +1,49 @@
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
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
1
35
  import { EventLogger } from "gd-eventlog";
2
36
  import { Observer } from "../../../base/types/observer";
3
- import IncyclistRoutesApi from "../../base/api";
4
37
  import { Route } from "../../base/model/route";
5
38
  import { addDetails } from "../../base/utils/route";
6
39
  import { RoutesDbLoader } from "./db";
7
40
  import { Loader } from "./types";
8
41
  import { sleep } from "../../../utils/sleep";
9
42
  import { settleWithLimit } from "../../../utils/settleWithLimit";
43
+ import { Injectable } from "../../../base/decorators";
44
+ import { useIncyclistRoutesApi } from "../../base/api/factory";
45
+ import { useUserSettings } from "../../../settings";
46
+ import { pascalCase } from "../../../utils";
10
47
  const ROUTE_DETAILS_CONCURRENCY = 4;
11
48
  const valid = (v) => (v !== undefined && v !== null);
12
49
  class ApiError extends Error {
@@ -28,191 +65,252 @@ const ExistingAndNotUpdated = (existing, descr) => {
28
65
  return ((existing.version || 0) >= (descr.version || 0))
29
66
  && (!isDeleted || (isDeleted && existing.isDownloaded));
30
67
  };
31
- export class RoutesApiLoader extends Loader {
32
- api;
33
- saveObserver;
34
- logger;
35
- constructor() {
36
- super();
37
- this.api = IncyclistRoutesApi.getInstance();
38
- this.logger = new EventLogger('RoutesApi');
39
- }
40
- load() {
41
- if (this.loadObserver)
68
+ let RoutesApiLoader = (() => {
69
+ let _classSuper = Loader;
70
+ let _instanceExtraInitializers = [];
71
+ let _getIncyclistRoutesApi_decorators;
72
+ let _getUserSettings_decorators;
73
+ return class RoutesApiLoader extends _classSuper {
74
+ static {
75
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
76
+ _getIncyclistRoutesApi_decorators = [Injectable];
77
+ _getUserSettings_decorators = [Injectable];
78
+ __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);
79
+ __esDecorate(this, null, _getUserSettings_decorators, { kind: "method", name: "getUserSettings", static: false, private: false, access: { has: obj => "getUserSettings" in obj, get: obj => obj.getUserSettings }, metadata: _metadata }, null, _instanceExtraInitializers);
80
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
81
+ }
82
+ api = __runInitializers(this, _instanceExtraInitializers);
83
+ saveObserver;
84
+ logger;
85
+ processed = [];
86
+ constructor() {
87
+ super();
88
+ this.api = this.getIncyclistRoutesApi().create();
89
+ this.logger = new EventLogger('RoutesApi');
90
+ }
91
+ load() {
92
+ this.processed = [];
93
+ if (this.loadObserver)
94
+ return this.loadObserver;
95
+ const enrichApi = (v, type) => ({ type, ...v });
96
+ const api = [
97
+ this.api.getRouteDescriptions({ type: 'gpx' }, true).then(v => v.map(e => enrichApi(e, 'gpx'))).catch(error => { throw new ApiError(error, 'gpx'); }),
98
+ this.api.getRouteDescriptions({ type: 'video' }, true).then(v => v.map(e => enrichApi(e, 'video'))).catch(error => { throw new ApiError(error, 'video'); }),
99
+ ];
100
+ this.loadObserver = new Observer();
101
+ Promise.allSettled(api).then(async (res) => {
102
+ await this.onLoadDone(api, res);
103
+ }).catch(err => { this.logger.logEvent({ message: 'could not process route list load', error: err.message }); });
104
+ const external = this.getExternalRouteServers();
105
+ const promises = [];
106
+ if (external.length) {
107
+ for (const externalApi of external) {
108
+ promises.push(externalApi.getRouteDescriptions({ type: 'video' }, true).then(v => v.map(e => enrichApi(e, 'video'))).catch(error => { throw new ApiError(error, 'video'); }));
109
+ }
110
+ Promise.allSettled(promises).then(async (res) => {
111
+ await this.onLoadDone(api, res, true);
112
+ }).catch(err => { this.logger.logEvent({ message: 'could not process route list load', error: err.message }); });
113
+ }
42
114
  return this.loadObserver;
43
- const enrichApi = (v, type) => ({ type, ...v });
44
- const api = [
45
- this.api.getRouteDescriptions({ type: 'gpx' }, true).then(v => v.map(e => enrichApi(e, 'gpx'))).catch(error => { throw new ApiError(error, 'gpx'); }),
46
- this.api.getRouteDescriptions({ type: 'video' }, true).then(v => v.map(e => enrichApi(e, 'video'))).catch(error => { throw new ApiError(error, 'video'); }),
47
- ];
48
- this.loadObserver = new Observer();
49
- Promise.allSettled(api).then(async (res) => {
50
- await this.onLoadDone(api, res);
51
- }).catch(err => { this.logger.logEvent({ message: 'could not process route list load', error: err.message }); });
52
- return this.loadObserver;
53
- }
54
- async onLoadDone(api, res) {
55
- const loadDetailRequired = [];
56
- for (let i = 0; i < res.length; i++) {
57
- const p = res[i];
58
- if (p.status !== 'fulfilled') {
59
- this.logger.logEvent({ message: 'could not load route list', reason: p.reason?.message, type: p.reason?.type });
60
- continue;
61
- }
62
- for (let j = 0; j < p.value.length; j++) {
63
- await this.processRouteFromApi(p.value[j], loadDetailRequired);
64
- }
65
- }
66
- this.loadObserver.emit('loaded');
67
- if (loadDetailRequired.length > 0) {
68
- await this.loadDetails(loadDetailRequired, true);
69
- }
70
- this.loadObserver.emit('done');
71
- await sleep(1);
72
- this.loadObserver.stop();
73
- delete this.loadObserver;
74
- }
75
- async processRouteFromApi(descr, items) {
76
- let description;
77
- const existing = this.getDescriptionFromDB(descr.routeId ?? descr.id);
78
- if (ExistingAndNotUpdated(existing, descr)) {
79
- const details = await this.getDetailsFromDB(existing.id);
80
- if (details) {
81
- return;
115
+ }
116
+ getExternalRouteServers() {
117
+ const externalConfig = this.getUserSettings().getValue('routes.servers', null);
118
+ const apis = [];
119
+ if (!externalConfig)
120
+ return apis;
121
+ Object.keys(externalConfig).forEach(key => {
122
+ const baseUrl = externalConfig[key];
123
+ this.logger.logEvent({ message: 'adding external route server', key, url: baseUrl });
124
+ const api = this.getIncyclistRoutesApi().create(key);
125
+ apis.push(api);
126
+ });
127
+ return apis;
128
+ }
129
+ async onLoadDone(api, res, isExternal = false) {
130
+ const loadDetailRequired = [];
131
+ for (let i = 0; i < res.length; i++) {
132
+ const p = res[i];
133
+ if (p.status !== 'fulfilled') {
134
+ this.logger.logEvent({ message: 'could not load route list', reason: p.reason?.message, type: p.reason?.type });
135
+ continue;
136
+ }
137
+ for (let j = 0; j < p.value.length; j++) {
138
+ if (isExternal && this.processed.includes(p.value[j].id))
139
+ continue;
140
+ await this.processRouteFromApi(p.value[j], loadDetailRequired);
141
+ }
142
+ }
143
+ this.loadObserver.emit('loaded');
144
+ if (loadDetailRequired.length > 0) {
145
+ await this.loadDetails(loadDetailRequired, true);
82
146
  }
83
- description = existing;
84
- this.logger.logEvent({ message: 'route details missing', id: description.id, title: description.title });
147
+ this.loadObserver.emit('done');
148
+ await sleep(1);
149
+ this.loadObserver.stop();
150
+ delete this.loadObserver;
85
151
  }
86
- else {
87
- description = this.buildRouteInfo(descr);
88
- if (!description) {
89
- this.logger.logEvent({ message: 'invalid route', descr });
152
+ async processRouteFromApi(descr, items) {
153
+ let description;
154
+ const existing = this.getDescriptionFromDB(descr.routeId ?? descr.id);
155
+ const alreadyProcessed = this.processed.includes(descr.routeId ?? descr.id);
156
+ if (alreadyProcessed)
90
157
  return;
158
+ if (ExistingAndNotUpdated(existing, descr)) {
159
+ this.processed.push(existing.id);
160
+ const details = await this.getDetailsFromDB(existing.id);
161
+ if (details) {
162
+ return;
163
+ }
164
+ description = existing;
165
+ this.logger.logEvent({ message: 'route details missing', id: description.id, title: description.title });
166
+ }
167
+ else {
168
+ description = this.buildRouteInfo(descr);
169
+ if (!description) {
170
+ this.logger.logEvent({ message: 'invalid route', descr });
171
+ return;
172
+ }
173
+ this.processed.push(descr.id);
174
+ if (!existing) {
175
+ this.logger.logEvent({ message: 'route added', id: description.id, title: description.title, ts: description.tsImported });
176
+ description.tsImported = Date.now();
177
+ }
178
+ else {
179
+ description.tsImported = existing.tsImported;
180
+ items.push({ route: new Route(description), added: false });
181
+ this.logger.logEvent({ message: 'route updated', id: description.id, title: description.title, from: existing.version, to: description.version, ts: Date.now(), tsImported: description.tsImported });
182
+ }
183
+ }
184
+ this.emitAndPrepareLoadDetails(description, items, existing);
185
+ }
186
+ emitAndPrepareLoadDetails(description, items, existing) {
187
+ const route = new Route(description);
188
+ const isComplete = this.isCompleted(route);
189
+ if (isComplete) {
190
+ this.verifyRouteHash(route);
91
191
  }
92
192
  if (!existing) {
93
- this.logger.logEvent({ message: 'route added', id: description.id, title: description.title, ts: description.tsImported });
94
- description.tsImported = Date.now();
193
+ this.emitRouteAdded(route);
194
+ items.push({ route, added: true });
195
+ if (isComplete) {
196
+ this.save(route, false).catch(err => { this.logger.logEvent({ message: 'could not save route', id: route.description.id, error: err.message }); });
197
+ }
95
198
  }
96
199
  else {
97
- description.tsImported = existing.tsImported;
98
- items.push({ route: new Route(description), added: false });
99
- this.logger.logEvent({ message: 'route updated', id: description.id, title: description.title, from: existing.version, to: description.version, ts: Date.now(), tsImported: description.tsImported });
200
+ this.save(route, true).catch(err => { this.logger.logEvent({ message: 'could not save route', id: route.description.id, error: err.message }); });
201
+ if (!isComplete)
202
+ items.push({ route, added: false });
100
203
  }
101
204
  }
102
- this.emitAndPrepareLoadDetails(description, items, existing);
103
- }
104
- emitAndPrepareLoadDetails(description, items, existing) {
105
- const route = new Route(description);
106
- const isComplete = this.isCompleted(route);
107
- if (isComplete) {
108
- this.verifyRouteHash(route);
109
- }
110
- if (!existing) {
111
- this.emitRouteAdded(route);
112
- items.push({ route, added: true });
113
- if (isComplete) {
114
- this.save(route, false).catch(err => { this.logger.logEvent({ message: 'could not save route', id: route.description.id, error: err.message }); });
205
+ stopLoad() {
206
+ this.loadObserver?.stop();
207
+ delete this.loadObserver;
208
+ }
209
+ getDescriptionFromDB(id) {
210
+ const db = new RoutesDbLoader();
211
+ return db.getDescription(id);
212
+ }
213
+ async getDetailsFromDB(id) {
214
+ const db = new RoutesDbLoader();
215
+ return await db.getDetails(id);
216
+ }
217
+ async save(route, enforcedWriteDetails = false) {
218
+ const db = new RoutesDbLoader();
219
+ await db.save(route, enforcedWriteDetails);
220
+ }
221
+ isCompleted(route) {
222
+ const descr = route.description;
223
+ if (descr.hasVideo) {
224
+ return valid(descr.points) && (valid(descr.videoUrl) || (descr.requiresDownload && valid(descr.downloadUrl)));
225
+ }
226
+ else {
227
+ return valid(descr.points);
115
228
  }
116
229
  }
117
- else {
118
- this.save(route, true).catch(err => { this.logger.logEvent({ message: 'could not save route', id: route.description.id, error: err.message }); });
119
- if (!isComplete)
120
- items.push({ route, added: false });
230
+ isPreviewMissing(route) {
231
+ const descr = route.description;
232
+ return descr?.hasVideo && !descr?.previewUrl;
121
233
  }
122
- }
123
- stopLoad() {
124
- this.loadObserver?.stop();
125
- delete this.loadObserver;
126
- }
127
- getDescriptionFromDB(id) {
128
- const db = new RoutesDbLoader();
129
- return db.getDescription(id);
130
- }
131
- async getDetailsFromDB(id) {
132
- const db = new RoutesDbLoader();
133
- return await db.getDetails(id);
134
- }
135
- async save(route, enforcedWriteDetails = false) {
136
- const db = new RoutesDbLoader();
137
- await db.save(route, enforcedWriteDetails);
138
- }
139
- isCompleted(route) {
140
- const descr = route.description;
141
- if (descr.hasVideo) {
142
- return valid(descr.points) && (valid(descr.videoUrl) || (descr.requiresDownload && valid(descr.downloadUrl)));
234
+ async loadDetailsFromRepo(items) {
235
+ const promises = items.map(i => this.getDetailsFromDB(i.route.description.id).then(details => { addDetails(i.route, details); }));
236
+ const res = await Promise.allSettled(promises);
237
+ const { failed } = await this.processLoadDetailsResult(res, items, false);
238
+ return failed;
143
239
  }
144
- else {
145
- return valid(descr.points);
240
+ async loadDetails(items, enforced = false) {
241
+ try {
242
+ const isUnique = (v, i, a) => {
243
+ return a.findIndex(item => item.route.description.id === v.route.description.id) === i;
244
+ };
245
+ items = items.filter((v, i, a) => isUnique(v, i, a));
246
+ }
247
+ catch (err) {
248
+ this.logger.logEvent({ message: 'error', fn: 'loadDetails#unique', error: err.message, stack: err.stack });
249
+ }
250
+ const failed = enforced ? items : await this.loadDetailsFromRepo(items);
251
+ const res = await settleWithLimit(failed, ROUTE_DETAILS_CONCURRENCY, i => this.getDetails(i.route));
252
+ await this.processLoadDetailsResult(res, items, true);
146
253
  }
147
- }
148
- isPreviewMissing(route) {
149
- const descr = route.description;
150
- return descr?.hasVideo && !descr?.previewUrl;
151
- }
152
- async loadDetailsFromRepo(items) {
153
- const promises = items.map(i => this.getDetailsFromDB(i.route.description.id).then(details => { addDetails(i.route, details); }));
154
- const res = await Promise.allSettled(promises);
155
- const { failed } = await this.processLoadDetailsResult(res, items, false);
156
- return failed;
157
- }
158
- async loadDetails(items, enforced = false) {
159
- try {
160
- const isUnique = (v, i, a) => {
161
- return a.findIndex(item => item.route.description.id === v.route.description.id) === i;
162
- };
163
- items = items.filter((v, i, a) => isUnique(v, i, a));
164
- }
165
- catch (err) {
166
- this.logger.logEvent({ message: 'error', fn: 'loadDetails#unique', error: err.message, stack: err.stack });
167
- }
168
- const failed = enforced ? items : await this.loadDetailsFromRepo(items);
169
- const res = await settleWithLimit(failed, ROUTE_DETAILS_CONCURRENCY, i => this.getDetails(i.route));
170
- await this.processLoadDetailsResult(res, items, true);
171
- }
172
- async processLoadDetailsResult(res, items, save) {
173
- const success = [];
174
- const failed = [];
175
- res.forEach((pr, idx) => {
176
- if (pr.status === 'fulfilled')
177
- success.push(items[idx]);
178
- else
179
- failed.push(items[idx]);
180
- });
181
- for (const element of success) {
182
- const item = element;
183
- this.emitRouteEvents(item.added === true, item.route);
184
- await this.verifyCountry(item.route);
185
- this.verifyRouteHash(item.route);
186
- if (save)
187
- this.save(item.route, true).catch(err => { this.logger.logEvent({ message: 'could not save route', id: item.route?.description?.id, error: err.message }); });
188
- }
189
- return { success, failed };
190
- }
191
- async getDetails(route) {
192
- const details = await this.api.getRouteDetails(route.description.legacyId || route.description.id);
193
- addDetails(route, details);
194
- }
195
- buildRouteInfo(descr, isLocal) {
196
- const { id, routeId, title, localizedTitle, country, distance, elevation, category, provider, video, requiresDownload, points, previewUrl, downloadUrl, routeHash, version, isDeleted } = descr;
197
- const data = { title, localizedTitle, country, distance, elevation, provider, category, previewUrl, requiresDownload, downloadUrl, routeHash, version, isDeleted };
198
- data.hasVideo = false;
199
- data.hasGpx = false;
200
- data.isLocal = isLocal || false;
201
- data.id = routeId || id;
202
- data.legacyId = routeId ? id : undefined;
203
- this.updateRouteCountry(data, { descr });
204
- this.updateRouteTitle(data, { descr });
205
- if (points)
206
- data.hasGpx = true;
207
- if (category?.toLowerCase() === 'demo')
208
- data.isDemo = true;
209
- if (video) {
210
- data.hasVideo = true;
211
- if (video.format)
212
- data.videoFormat = video.format;
213
- if (video.url && !data.videoUrl)
214
- data.videoUrl = video.url;
215
- }
216
- return data;
217
- }
218
- }
254
+ async processLoadDetailsResult(res, items, save) {
255
+ const success = [];
256
+ const failed = [];
257
+ res.forEach((pr, idx) => {
258
+ if (pr.status === 'fulfilled')
259
+ success.push(items[idx]);
260
+ else
261
+ failed.push(items[idx]);
262
+ });
263
+ for (const element of success) {
264
+ const item = element;
265
+ this.emitRouteEvents(true, item.route);
266
+ await this.verifyCountry(item.route);
267
+ this.verifyRouteHash(item.route);
268
+ if (save)
269
+ this.save(item.route, true).catch(err => { this.logger.logEvent({ message: 'could not save route', id: item.route?.description?.id, error: err.message }); });
270
+ }
271
+ return { success, failed };
272
+ }
273
+ async getDetails(route) {
274
+ let api = this.api;
275
+ if (route.description.apiServer) {
276
+ api = this.getIncyclistRoutesApi().create(route.description.apiServer);
277
+ }
278
+ const details = await api.getRouteDetails(route.description.legacyId || route.description.id);
279
+ addDetails(route, details);
280
+ }
281
+ buildRouteInfo(descr, isLocal) {
282
+ const { id, routeId, title, localizedTitle, country, distance, elevation, category, provider, video, requiresDownload, points, previewUrl, downloadUrl, routeHash, version, isDeleted, apiServer } = descr;
283
+ const data = { title, localizedTitle, country, distance, elevation, provider, category, previewUrl, requiresDownload, downloadUrl, routeHash, version, isDeleted };
284
+ data.hasVideo = false;
285
+ data.hasGpx = false;
286
+ data.isLocal = isLocal || false;
287
+ data.id = routeId || id;
288
+ data.legacyId = routeId ? id : undefined;
289
+ this.updateRouteCountry(data, { descr });
290
+ this.updateRouteTitle(data, { descr });
291
+ if (points)
292
+ data.hasGpx = true;
293
+ if (category?.toLowerCase() === 'demo')
294
+ data.isDemo = true;
295
+ if (video) {
296
+ data.hasVideo = true;
297
+ if (video.format)
298
+ data.videoFormat = video.format;
299
+ if (video.url && !data.videoUrl)
300
+ data.videoUrl = video.url;
301
+ }
302
+ if (apiServer) {
303
+ data.apiServer = apiServer;
304
+ data.source = pascalCase(apiServer);
305
+ }
306
+ return data;
307
+ }
308
+ getIncyclistRoutesApi() {
309
+ return useIncyclistRoutesApi();
310
+ }
311
+ getUserSettings() {
312
+ return useUserSettings();
313
+ }
314
+ };
315
+ })();
316
+ export { RoutesApiLoader };