incyclist-services 1.9.23 → 1.9.25

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,12 @@ let ConnectedAppService = (() => {
99
99
  this.init();
100
100
  return this.isInitialized;
101
101
  }
102
+ getSupportedOperations() {
103
+ return [];
104
+ }
105
+ getDefaultOperations() {
106
+ return [];
107
+ }
102
108
  getUserSettings() {
103
109
  return (0, settings_1.useUserSettings)();
104
110
  }
@@ -121,6 +121,12 @@ let IntervalsAppConnection = (() => {
121
121
  this.api = new api_2.IntervalsApi();
122
122
  return this.api;
123
123
  }
124
+ getSupportedOperations() {
125
+ return ['ActivityUpload', 'WorkoutDownload'];
126
+ }
127
+ getDefaultOperations() {
128
+ return ['ActivityUpload', 'WorkoutDownload'];
129
+ }
124
130
  initAuth() {
125
131
  let isInitialized;
126
132
  try {
@@ -109,6 +109,12 @@ let KomootAppConnection = (() => {
109
109
  getApi() {
110
110
  return this.api;
111
111
  }
112
+ getSupportedOperations() {
113
+ return ['ActivityUpload', 'RouteDownload'];
114
+ }
115
+ getDefaultOperations() {
116
+ return ['RouteDownload'];
117
+ }
112
118
  initAuth() {
113
119
  const api = this.getApi();
114
120
  if (this.credentials && api) {
@@ -65,18 +65,11 @@ let AppsService = (() => {
65
65
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
66
66
  __runInitializers(_classThis, _classExtraInitializers);
67
67
  }
68
- services = (__runInitializers(this, _instanceExtraInitializers), {
69
- ActivityUpload: ['strava', 'intervals', 'komoot'],
70
- WorkoutUpload: [],
71
- WorkoutDownload: ['intervals'],
72
- ActivityDownload: [],
73
- RouteDownload: ['komoot']
74
- });
75
- serviceMap = [
68
+ serviceMap = (__runInitializers(this, _instanceExtraInitializers), [
76
69
  { name: 'Strava', key: 'strava', iconUrl: 'https://static.cdnlogo.com/logos/s/42/strava-wordmark.svg', connection: new base_1.StravaAppConnection() },
77
70
  { name: 'Komoot', key: 'komoot', iconUrl: 'https://www.komoot.com/assets/4d8ae313eec53e6e.svg', connection: new komoot_1.KomootAppConnection() },
78
71
  { name: 'Intervals.icu', key: 'intervals', iconUrl: 'images/intervals.png', connection: new IntervalsAppConnection_1.IntervalsAppConnection() },
79
- ];
72
+ ]);
80
73
  constructor() {
81
74
  super('AppsService');
82
75
  }
@@ -100,6 +93,8 @@ let AppsService = (() => {
100
93
  if (!entry?.connection)
101
94
  return false;
102
95
  const success = await entry.connection.connect(credentials);
96
+ if (!this.hasSettings(app))
97
+ this.storeInitialSettings(app);
103
98
  this.emit('connected', app, success);
104
99
  return success;
105
100
  }
@@ -127,18 +122,22 @@ let AppsService = (() => {
127
122
  isEnabled(app, operation) {
128
123
  if (!this.isConnected(app))
129
124
  return false;
125
+ if (!this.hasSettings(app))
126
+ this.storeInitialSettings(app);
130
127
  const supported = this.getAppOperationSettings(app);
131
128
  const config = supported.find(oc => oc.operation === operation);
132
129
  return config?.enabled;
133
130
  }
134
131
  getAppOperationSettings(app) {
135
- const serviceIds = Object.keys(this.services);
132
+ const connectedApp = this.getAppConnection(app);
133
+ if (!connectedApp)
134
+ return [];
135
+ const supported = connectedApp.getSupportedOperations();
136
+ const defaults = connectedApp.getDefaultOperations();
136
137
  const operations = [];
137
- serviceIds.forEach(operation => {
138
- if (this.services[operation].includes(app)) {
139
- const enabled = this.getSettings(`preferences.${app}.${operation}.enabled`, true);
140
- operations.push({ operation, enabled });
141
- }
138
+ supported.forEach(operation => {
139
+ const enabled = this.getSettings(`preferences.${app}.${operation}.enabled`, defaults.includes(operation));
140
+ operations.push({ operation, enabled });
142
141
  });
143
142
  return operations;
144
143
  }
@@ -159,7 +158,14 @@ let AppsService = (() => {
159
158
  return [];
160
159
  }
161
160
  getAvailableServices(operation) {
162
- return this.services[operation];
161
+ const serviceIds = this.getServiceIDs();
162
+ const supported = [];
163
+ serviceIds.forEach(serviceKey => {
164
+ if (this.getAppConnection(serviceKey)?.getSupportedOperations().includes(operation)) {
165
+ supported.push(serviceKey);
166
+ }
167
+ });
168
+ return supported;
163
169
  }
164
170
  getName(key) {
165
171
  const found = this.serviceMap.find(r => r.key === key);
@@ -169,6 +175,32 @@ let AppsService = (() => {
169
175
  const found = this.serviceMap.find(r => r.name === name);
170
176
  return found ? found.key : name;
171
177
  }
178
+ hasSettings(app) {
179
+ const settings = this.getUserSettings().getValue(`preferences.${app}`, null);
180
+ return settings !== null;
181
+ }
182
+ storeInitialSettings(app) {
183
+ if (this.hasSettings(app))
184
+ return;
185
+ const connection = this.getAppConnection(app);
186
+ if (!connection)
187
+ return;
188
+ const supported = connection.getSupportedOperations();
189
+ const defaults = connection.getDefaultOperations();
190
+ for (const operation of supported) {
191
+ const isDefault = defaults.includes(operation);
192
+ this.getUserSettings().set(`preferences.${app}.${operation}.enabled`, isDefault);
193
+ }
194
+ }
195
+ getServiceIDs() {
196
+ return this.serviceMap.map(m => m.key);
197
+ }
198
+ getAppConnections() {
199
+ return this.serviceMap.map(m => m.connection);
200
+ }
201
+ getAppConnection(serviceKey) {
202
+ return this.serviceMap.find(m => serviceKey === m.key)?.connection;
203
+ }
172
204
  getAppDisplayProps(key) {
173
205
  const entry = this.serviceMap.find(e => e.key === key);
174
206
  const { name, iconUrl } = entry;
@@ -119,6 +119,12 @@ let StravaAppConnection = (() => {
119
119
  this.api = new api_2.StravaApi();
120
120
  return this.api;
121
121
  }
122
+ getSupportedOperations() {
123
+ return ['ActivityUpload'];
124
+ }
125
+ getDefaultOperations() {
126
+ return ['ActivityUpload'];
127
+ }
122
128
  initAuth() {
123
129
  let isInitialized;
124
130
  try {
@@ -0,0 +1,32 @@
1
+ export const StravaRouteSubTypeToString = {
2
+ 1: 'racebike',
3
+ 2: 'mtb',
4
+ 3: 'cross',
5
+ 4: 'trail',
6
+ 5: 'mixed'
7
+ };
8
+ export const StringToStravaRouteSubType = {
9
+ racebike: 1,
10
+ mtb: 2,
11
+ cross: 3,
12
+ trail: 4,
13
+ mixed: 5
14
+ };
15
+ export const StravaRouteTypeToString = {
16
+ 1: 'ride',
17
+ 2: 'run',
18
+ 3: 'walk',
19
+ 4: 'hike',
20
+ 5: 'trailrun',
21
+ 6: 'gravel',
22
+ 7: 'mtb'
23
+ };
24
+ export const StringToStravaRouteType = {
25
+ ride: 1,
26
+ run: 2,
27
+ walk: 3,
28
+ hike: 4,
29
+ trailrun: 5,
30
+ gravel: 6,
31
+ mtb: 7
32
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -96,6 +96,12 @@ let ConnectedAppService = (() => {
96
96
  this.init();
97
97
  return this.isInitialized;
98
98
  }
99
+ getSupportedOperations() {
100
+ return [];
101
+ }
102
+ getDefaultOperations() {
103
+ return [];
104
+ }
99
105
  getUserSettings() {
100
106
  return useUserSettings();
101
107
  }
@@ -118,6 +118,12 @@ let IntervalsAppConnection = (() => {
118
118
  this.api = new IntervalsApi();
119
119
  return this.api;
120
120
  }
121
+ getSupportedOperations() {
122
+ return ['ActivityUpload', 'WorkoutDownload'];
123
+ }
124
+ getDefaultOperations() {
125
+ return ['ActivityUpload', 'WorkoutDownload'];
126
+ }
121
127
  initAuth() {
122
128
  let isInitialized;
123
129
  try {
@@ -106,6 +106,12 @@ let KomootAppConnection = (() => {
106
106
  getApi() {
107
107
  return this.api;
108
108
  }
109
+ getSupportedOperations() {
110
+ return ['ActivityUpload', 'RouteDownload'];
111
+ }
112
+ getDefaultOperations() {
113
+ return ['RouteDownload'];
114
+ }
109
115
  initAuth() {
110
116
  const api = this.getApi();
111
117
  if (this.credentials && api) {
@@ -62,18 +62,11 @@ let AppsService = (() => {
62
62
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
63
63
  __runInitializers(_classThis, _classExtraInitializers);
64
64
  }
65
- services = (__runInitializers(this, _instanceExtraInitializers), {
66
- ActivityUpload: ['strava', 'intervals', 'komoot'],
67
- WorkoutUpload: [],
68
- WorkoutDownload: ['intervals'],
69
- ActivityDownload: [],
70
- RouteDownload: ['komoot']
71
- });
72
- serviceMap = [
65
+ serviceMap = (__runInitializers(this, _instanceExtraInitializers), [
73
66
  { name: 'Strava', key: 'strava', iconUrl: 'https://static.cdnlogo.com/logos/s/42/strava-wordmark.svg', connection: new StravaAppConnection() },
74
67
  { name: 'Komoot', key: 'komoot', iconUrl: 'https://www.komoot.com/assets/4d8ae313eec53e6e.svg', connection: new KomootAppConnection() },
75
68
  { name: 'Intervals.icu', key: 'intervals', iconUrl: 'images/intervals.png', connection: new IntervalsAppConnection() },
76
- ];
69
+ ]);
77
70
  constructor() {
78
71
  super('AppsService');
79
72
  }
@@ -97,6 +90,8 @@ let AppsService = (() => {
97
90
  if (!entry?.connection)
98
91
  return false;
99
92
  const success = await entry.connection.connect(credentials);
93
+ if (!this.hasSettings(app))
94
+ this.storeInitialSettings(app);
100
95
  this.emit('connected', app, success);
101
96
  return success;
102
97
  }
@@ -124,18 +119,22 @@ let AppsService = (() => {
124
119
  isEnabled(app, operation) {
125
120
  if (!this.isConnected(app))
126
121
  return false;
122
+ if (!this.hasSettings(app))
123
+ this.storeInitialSettings(app);
127
124
  const supported = this.getAppOperationSettings(app);
128
125
  const config = supported.find(oc => oc.operation === operation);
129
126
  return config?.enabled;
130
127
  }
131
128
  getAppOperationSettings(app) {
132
- const serviceIds = Object.keys(this.services);
129
+ const connectedApp = this.getAppConnection(app);
130
+ if (!connectedApp)
131
+ return [];
132
+ const supported = connectedApp.getSupportedOperations();
133
+ const defaults = connectedApp.getDefaultOperations();
133
134
  const operations = [];
134
- serviceIds.forEach(operation => {
135
- if (this.services[operation].includes(app)) {
136
- const enabled = this.getSettings(`preferences.${app}.${operation}.enabled`, true);
137
- operations.push({ operation, enabled });
138
- }
135
+ supported.forEach(operation => {
136
+ const enabled = this.getSettings(`preferences.${app}.${operation}.enabled`, defaults.includes(operation));
137
+ operations.push({ operation, enabled });
139
138
  });
140
139
  return operations;
141
140
  }
@@ -156,7 +155,14 @@ let AppsService = (() => {
156
155
  return [];
157
156
  }
158
157
  getAvailableServices(operation) {
159
- return this.services[operation];
158
+ const serviceIds = this.getServiceIDs();
159
+ const supported = [];
160
+ serviceIds.forEach(serviceKey => {
161
+ if (this.getAppConnection(serviceKey)?.getSupportedOperations().includes(operation)) {
162
+ supported.push(serviceKey);
163
+ }
164
+ });
165
+ return supported;
160
166
  }
161
167
  getName(key) {
162
168
  const found = this.serviceMap.find(r => r.key === key);
@@ -166,6 +172,32 @@ let AppsService = (() => {
166
172
  const found = this.serviceMap.find(r => r.name === name);
167
173
  return found ? found.key : name;
168
174
  }
175
+ hasSettings(app) {
176
+ const settings = this.getUserSettings().getValue(`preferences.${app}`, null);
177
+ return settings !== null;
178
+ }
179
+ storeInitialSettings(app) {
180
+ if (this.hasSettings(app))
181
+ return;
182
+ const connection = this.getAppConnection(app);
183
+ if (!connection)
184
+ return;
185
+ const supported = connection.getSupportedOperations();
186
+ const defaults = connection.getDefaultOperations();
187
+ for (const operation of supported) {
188
+ const isDefault = defaults.includes(operation);
189
+ this.getUserSettings().set(`preferences.${app}.${operation}.enabled`, isDefault);
190
+ }
191
+ }
192
+ getServiceIDs() {
193
+ return this.serviceMap.map(m => m.key);
194
+ }
195
+ getAppConnections() {
196
+ return this.serviceMap.map(m => m.connection);
197
+ }
198
+ getAppConnection(serviceKey) {
199
+ return this.serviceMap.find(m => serviceKey === m.key)?.connection;
200
+ }
169
201
  getAppDisplayProps(key) {
170
202
  const entry = this.serviceMap.find(e => e.key === key);
171
203
  const { name, iconUrl } = entry;
@@ -116,6 +116,12 @@ let StravaAppConnection = (() => {
116
116
  this.api = new StravaApi();
117
117
  return this.api;
118
118
  }
119
+ getSupportedOperations() {
120
+ return ['ActivityUpload'];
121
+ }
122
+ getDefaultOperations() {
123
+ return ['ActivityUpload'];
124
+ }
119
125
  initAuth() {
120
126
  let isInitialized;
121
127
  try {
@@ -0,0 +1,214 @@
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
+ };
35
+ import { useAppsService } from "../../../apps";
36
+ import { Injectable } from "../../../base/decorators";
37
+ import { IncyclistService } from "../../../base/service";
38
+ import { Observer } from "../../../base/types";
39
+ import { useUserSettings } from "../../../settings";
40
+ import { waitNextTick } from "../../../utils";
41
+ import { Route } from "../../base/model/route";
42
+ import { RouteSyncFactory } from "../factory";
43
+ let BaseSyncProvider = (() => {
44
+ let _classSuper = IncyclistService;
45
+ let _instanceExtraInitializers = [];
46
+ let _getUserSettings_decorators;
47
+ let _getRouteListService_decorators;
48
+ let _getRouteSyncFactory_decorators;
49
+ let _getAppsService_decorators;
50
+ return class BaseSyncProvider extends _classSuper {
51
+ static {
52
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
53
+ _getUserSettings_decorators = [Injectable];
54
+ _getRouteListService_decorators = [Injectable];
55
+ _getRouteSyncFactory_decorators = [Injectable];
56
+ _getAppsService_decorators = [Injectable];
57
+ __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);
58
+ __esDecorate(this, null, _getRouteListService_decorators, { kind: "method", name: "getRouteListService", static: false, private: false, access: { has: obj => "getRouteListService" in obj, get: obj => obj.getRouteListService }, metadata: _metadata }, null, _instanceExtraInitializers);
59
+ __esDecorate(this, null, _getRouteSyncFactory_decorators, { kind: "method", name: "getRouteSyncFactory", static: false, private: false, access: { has: obj => "getRouteSyncFactory" in obj, get: obj => obj.getRouteSyncFactory }, metadata: _metadata }, null, _instanceExtraInitializers);
60
+ __esDecorate(this, null, _getAppsService_decorators, { kind: "method", name: "getAppsService", static: false, private: false, access: { has: obj => "getAppsService" in obj, get: obj => obj.getAppsService }, metadata: _metadata }, null, _instanceExtraInitializers);
61
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
62
+ }
63
+ lastSyncTS = __runInitializers(this, _instanceExtraInitializers);
64
+ observer;
65
+ stopRequested;
66
+ sync() {
67
+ if (this.observer)
68
+ return this.observer;
69
+ this.observer = new Observer();
70
+ this.observer.once('done', () => {
71
+ waitNextTick().then(() => {
72
+ this.stopRequested = false;
73
+ delete this.observer;
74
+ }).catch(err => { this.logError(err, 'sync'); });
75
+ });
76
+ this.observer.once('stop', () => { this.stopSync(); });
77
+ this.loadTours().catch(err => { this.logError(err, 'sync'); });
78
+ return this.observer;
79
+ }
80
+ isConnected() {
81
+ if (this.getApi().isAuthenticated()) {
82
+ return true;
83
+ }
84
+ const connected = this.getConnection().isConnected();
85
+ return connected;
86
+ }
87
+ getOriginalId(route) {
88
+ const app = this.getConnection().getAppKey();
89
+ const idStr = route.description?.id;
90
+ if (!idStr.startsWith(`${app}:`))
91
+ return;
92
+ return idStr.split(':')[1];
93
+ }
94
+ async loadTours() {
95
+ const app = this.getConnection().getAppKey();
96
+ if (!this.getAppsService().isEnabled(app, 'RouteDownload')) {
97
+ await waitNextTick();
98
+ this.observer.emit('done');
99
+ return [];
100
+ }
101
+ this.logEvent({ message: `start ${app} route sync` });
102
+ const { routes, done, error } = await this.loadRoutesFromApi();
103
+ if (error) {
104
+ this.logEvent({ message: `${app} route sync failed` });
105
+ }
106
+ else if (done) {
107
+ const { added, updated, deleted } = this.checkTours(routes);
108
+ this.updateLastSyncTime();
109
+ this.observer.emit('done');
110
+ this.logEvent({ message: `${app} route sync finished`, added: added?.length, updated: updated?.length, deleted: deleted.length });
111
+ return added;
112
+ }
113
+ else {
114
+ this.observer.emit('done');
115
+ this.logEvent({ message: `${app} route sync stopped` });
116
+ return [];
117
+ }
118
+ }
119
+ checkTours(candidates) {
120
+ const app = this.getConnection().getAppKey();
121
+ const routes = this.getRouteListService()?.getAllAppRoutes(app) ?? [];
122
+ const matched = routes.map(r => ({ id: r.id, matched: false }));
123
+ const added = [];
124
+ const updated = [];
125
+ candidates.forEach(tour => {
126
+ const summary = this.getRouteSyncSummary(tour);
127
+ const id = `${app}:${summary.id}`;
128
+ const route = routes.find(route => route.id === id);
129
+ if (!route) {
130
+ added.push(tour);
131
+ }
132
+ else if (route.isDeleted) {
133
+ const matchRecord = matched.find(r => r.id === id);
134
+ if (matchRecord)
135
+ matchRecord.matched = true;
136
+ }
137
+ else {
138
+ const matchRecord = matched.find(r => r.id === id);
139
+ if (matchRecord)
140
+ matchRecord.matched = true;
141
+ const routeTS = route.tsLastChange ?? 0;
142
+ const tourTS = (new Date(summary.lastUpdate)).valueOf();
143
+ if (tourTS > routeTS) {
144
+ const description = this.buildRouteInfo(tour);
145
+ updated.push(new Route(description));
146
+ }
147
+ }
148
+ });
149
+ const unmatched = matched.filter(r => !r.matched);
150
+ const deleted = unmatched.map(r => r.id);
151
+ this.emitUpdates(added, updated, deleted);
152
+ return { added, updated, deleted };
153
+ }
154
+ stopSync() {
155
+ this.stopRequested = true;
156
+ }
157
+ emitUpdates(added, updated, deleted) {
158
+ if (added.length > 0) {
159
+ this.emitAdded(added);
160
+ }
161
+ if (updated.length > 0) {
162
+ this.emitUpdated(updated);
163
+ }
164
+ if (deleted.length > 0) {
165
+ this.emitDeleted(deleted);
166
+ }
167
+ }
168
+ emitAdded(tours) {
169
+ this.observer.emit('added', tours.map(tour => this.buildRouteInfo(tour)));
170
+ }
171
+ emitUpdated(routes) {
172
+ this.observer.emit('updated', routes);
173
+ }
174
+ emitDeleted(routes) {
175
+ this.observer.emit('deleted', routes);
176
+ }
177
+ getLastSyncTime() {
178
+ const lastSyncTS = this.lastSyncTS ?? 0;
179
+ const key = this.getSyncKey();
180
+ this.lastSyncTS = Math.max(lastSyncTS, this.getUserSettings().get(key, lastSyncTS));
181
+ return this.lastSyncTS > 0 ? new Date(this.lastSyncTS) : undefined;
182
+ }
183
+ getCreatedFilter(days = 365) {
184
+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000);
185
+ }
186
+ updateLastSyncTime() {
187
+ this.lastSyncTS = Date.now();
188
+ this.saveLastSyncTime();
189
+ }
190
+ saveLastSyncTime() {
191
+ if (!this.lastSyncTS)
192
+ return;
193
+ const key = this.getSyncKey();
194
+ this.getUserSettings().set(key, this.lastSyncTS);
195
+ }
196
+ getSyncKey() {
197
+ const app = this.getConnection().getAppKey();
198
+ return `apps.${app}.lastSync`;
199
+ }
200
+ getUserSettings() {
201
+ return useUserSettings();
202
+ }
203
+ getRouteListService() {
204
+ return this.getRouteSyncFactory().getRouteList();
205
+ }
206
+ getRouteSyncFactory() {
207
+ return new RouteSyncFactory();
208
+ }
209
+ getAppsService() {
210
+ return useAppsService();
211
+ }
212
+ };
213
+ })();
214
+ export { BaseSyncProvider };
@@ -0,0 +1,124 @@
1
+ import { StravaAppConnection } from "../../../apps";
2
+ import { BaseSyncProvider } from "../base/provider";
3
+ import { GPXParser } from "../../base/parsers/gpx";
4
+ import { calculateDistance } from "../../../utils/geo";
5
+ import { RouteSyncFactory } from "../factory";
6
+ import { sleep } from "../../../utils/sleep";
7
+ const PAGE_LIMIT = 50;
8
+ const SPORTS_FILTER = 'ride';
9
+ export class StravaSyncProvider extends BaseSyncProvider {
10
+ constructor() {
11
+ super('StravaSync');
12
+ }
13
+ async loadDetails(route) {
14
+ try {
15
+ this.logEvent({ message: 'load route details', id: route?.description?.id, title: route?.description?.title });
16
+ const id = this.getOriginalId(route);
17
+ if (!id)
18
+ return;
19
+ const gpxContent = await this.getApi().getRouteAsGPX(id);
20
+ if (typeof gpxContent == 'string') {
21
+ await this.addRouteDetails(route, gpxContent);
22
+ return route;
23
+ }
24
+ else {
25
+ const error = gpxContent.error;
26
+ throw new Error(error);
27
+ }
28
+ }
29
+ catch (err) {
30
+ this.logError(err, 'loadDetails', { id: route?.description?.id, title: route?.description?.title });
31
+ }
32
+ }
33
+ async loadRoutesFromApi() {
34
+ const api = this.getApi();
35
+ let page = 1;
36
+ let done = false;
37
+ let error = false;
38
+ const routes = [];
39
+ while (!done && !this.stopRequested) {
40
+ try {
41
+ const filters = { sport: this.getSportFilter() };
42
+ const pageRoutes = await api.getLoggedInAthleteRoutes({ page, per_page: PAGE_LIMIT }, filters);
43
+ if (Array.isArray(pageRoutes) && pageRoutes.length > 0) {
44
+ routes.push(...pageRoutes);
45
+ page++;
46
+ }
47
+ else {
48
+ done = true;
49
+ }
50
+ await sleep(100);
51
+ }
52
+ catch (err) {
53
+ this.logEvent({ message: 'could not load tours', reason: err.message });
54
+ done = true;
55
+ error = true;
56
+ }
57
+ }
58
+ return { routes, done, error };
59
+ }
60
+ async addRouteDetails(route, gpx) {
61
+ const parser = new GPXParser();
62
+ const parsed = await parser.parseFromString(gpx);
63
+ const points = parsed.details.points;
64
+ const last = points.at(-1);
65
+ const first = points[0];
66
+ const totalDistance = last.routeDistance;
67
+ const totalElevation = last.elevationGain;
68
+ const descr = route.description;
69
+ if (descr.distance !== totalDistance)
70
+ descr.distance = totalDistance;
71
+ if (descr.elevation !== totalElevation)
72
+ descr.elevation = totalElevation;
73
+ descr.isLoop = (calculateDistance(first.lat, first.lng, last.lat, last.lng) < 50);
74
+ route.addDetails({
75
+ id: descr.id,
76
+ title: descr.title,
77
+ points,
78
+ country: descr.country,
79
+ distance: descr.distance,
80
+ elevation: descr.elevation,
81
+ category: descr.category,
82
+ });
83
+ if (!descr.country && route.points?.length > 0) {
84
+ this.logEvent({ message: 'route update required (country)', route: route.title });
85
+ const updated = await route.updateCountryFromPoints();
86
+ if (updated) {
87
+ this.logEvent({ message: 'route updated (country)', route: route.title, country: route.description?.country });
88
+ }
89
+ }
90
+ descr.points = points;
91
+ }
92
+ getSportFilter() {
93
+ return SPORTS_FILTER;
94
+ }
95
+ getRouteSyncSummary(route) {
96
+ return {
97
+ id: route.id_str ?? route.id?.toString(),
98
+ lastUpdate: route.updated_at,
99
+ creation: route.created_at
100
+ };
101
+ }
102
+ buildRouteInfo(route) {
103
+ const info = {
104
+ hasGpx: true,
105
+ hasVideo: false,
106
+ id: 'strava:' + (route.id_str ?? route.id?.toString()),
107
+ title: route.name,
108
+ elevation: route.elevation_gain,
109
+ distance: route.distance,
110
+ category: 'external',
111
+ source: 'strava',
112
+ tsLastChange: (new Date(route.updated_at)).valueOf()
113
+ };
114
+ return info;
115
+ }
116
+ getApi() {
117
+ return this.getConnection().getApi();
118
+ }
119
+ getConnection() {
120
+ return new StravaAppConnection();
121
+ }
122
+ }
123
+ const factory = new RouteSyncFactory();
124
+ factory.add('strava', new StravaSyncProvider());
@@ -0,0 +1,5 @@
1
+ import { StravaRouteSubType, StravaRouteType } from "./types";
2
+ export declare const StravaRouteSubTypeToString: Record<StravaRouteSubType, string>;
3
+ export declare const StringToStravaRouteSubType: Record<string, StravaRouteSubType>;
4
+ export declare const StravaRouteTypeToString: Record<StravaRouteType, string>;
5
+ export declare const StringToStravaRouteType: Record<string, StravaRouteType>;
@@ -0,0 +1,3 @@
1
+ export interface IExternalAppApi {
2
+ isAuthenticated(): boolean;
3
+ }
@@ -1,5 +1,5 @@
1
1
  import { IncyclistService } from "../../../base/service";
2
- import { IConnectedApp } from "../../types";
2
+ import { AppsOperation, IConnectedApp } from "../../types";
3
3
  import { AppCredentials } from "../types";
4
4
  export declare class ConnectedAppService<C extends AppCredentials> extends IncyclistService implements IConnectedApp {
5
5
  protected service: any;
@@ -16,5 +16,7 @@ export declare class ConnectedAppService<C extends AppCredentials> extends Incyc
16
16
  protected initAuth(): boolean;
17
17
  protected checkAuth(): boolean;
18
18
  protected ensureInitialized(): boolean;
19
+ getSupportedOperations(): AppsOperation[];
20
+ getDefaultOperations(): AppsOperation[];
19
21
  protected getUserSettings(): import("../../../settings").UserSettingsService;
20
22
  }
@@ -1,5 +1,6 @@
1
1
  import { IntervalsApi, IntervalsConfig } from "../base/api";
2
2
  import { ConnectedAppService } from "../base/app";
3
+ import { AppsOperation } from "../types";
3
4
  import { IntervalsCredentials } from "./types";
4
5
  export declare class IntervalsAppConnection extends ConnectedAppService<IntervalsCredentials> {
5
6
  protected config: IntervalsConfig;
@@ -11,6 +12,8 @@ export declare class IntervalsAppConnection extends ConnectedAppService<Interval
11
12
  isConnected(): boolean;
12
13
  getCredentials(): IntervalsCredentials;
13
14
  getApi(): IntervalsApi;
15
+ getSupportedOperations(): AppsOperation[];
16
+ getDefaultOperations(): AppsOperation[];
14
17
  protected initAuth(): boolean;
15
18
  protected updateConfig(config: IntervalsConfig): void;
16
19
  protected saveCredentials(config?: IntervalsConfig): void;
@@ -1,5 +1,6 @@
1
1
  import { KomootApi } from "../base/api";
2
2
  import { ConnectedAppService } from "../base/app";
3
+ import { AppsOperation } from "../types";
3
4
  import { KomootAuth, KomootCredentials } from "./types";
4
5
  export declare class KomootAppConnection extends ConnectedAppService<KomootCredentials> {
5
6
  protected _isConnecting: any;
@@ -11,6 +12,8 @@ export declare class KomootAppConnection extends ConnectedAppService<KomootCrede
11
12
  isConnected(): boolean;
12
13
  getCredentials(): KomootCredentials;
13
14
  getApi(): KomootApi;
15
+ getSupportedOperations(): AppsOperation[];
16
+ getDefaultOperations(): AppsOperation[];
14
17
  protected initAuth(): boolean;
15
18
  protected checkAuth(): boolean;
16
19
  protected getAuthConfig(): KomootAuth | KomootCredentials;
@@ -1,9 +1,8 @@
1
1
  import { ActivityUploadFactory } from "../activities/upload";
2
2
  import { IncyclistService } from "../base/service";
3
3
  import { AppCredentials } from "./base/types";
4
- import { AppDefinition, AppsIntergationSpec, AppsOperation } from "./types";
4
+ import { AppDefinition, AppsOperation, IConnectedApp } from "./types";
5
5
  export declare class AppsService extends IncyclistService {
6
- protected readonly services: AppsIntergationSpec;
7
6
  protected readonly serviceMap: Array<AppDefinition>;
8
7
  constructor();
9
8
  openSettings(): {
@@ -26,6 +25,11 @@ export declare class AppsService extends IncyclistService {
26
25
  getAvailableServices(operation: AppsOperation): Array<string>;
27
26
  getName(key: string): string;
28
27
  getKey(name: string): string;
28
+ protected hasSettings(app: string): boolean;
29
+ protected storeInitialSettings(app: string): void;
30
+ protected getServiceIDs(): Array<string>;
31
+ protected getAppConnections(): Array<IConnectedApp>;
32
+ protected getAppConnection(serviceKey: string): IConnectedApp | undefined;
29
33
  protected getAppDisplayProps(key: string): {
30
34
  name: string;
31
35
  key: string;
@@ -1,5 +1,6 @@
1
1
  import { StravaApi, StravaConfig } from "../base/api";
2
2
  import { ConnectedAppService } from "../base/app";
3
+ import { AppsOperation } from "../types";
3
4
  import { StravaCredentials } from "./types";
4
5
  export declare class StravaAppConnection extends ConnectedAppService<StravaCredentials> {
5
6
  protected config: StravaConfig;
@@ -12,6 +13,8 @@ export declare class StravaAppConnection extends ConnectedAppService<StravaCrede
12
13
  isConnected(): boolean;
13
14
  getCredentials(): StravaCredentials;
14
15
  getApi(): StravaApi;
16
+ getSupportedOperations(): AppsOperation[];
17
+ getDefaultOperations(): AppsOperation[];
15
18
  protected initAuth(): boolean;
16
19
  protected updateConfig(config: StravaConfig): void;
17
20
  protected saveCredentials(config?: StravaConfig): void;
@@ -1,6 +1,6 @@
1
1
  import { ConnectedAppService } from "./base";
2
2
  export type AppsOperation = 'ActivityUpload' | 'WorkoutUpload' | 'WorkoutDownload' | 'RouteDownload' | 'ActivityDownload';
3
- export type AppsIntergationSpec = Record<AppsOperation, Array<string>>;
3
+ export type AppsIntergationSpec = Map<AppsOperation, Array<string>>;
4
4
  export type AppDefinition = {
5
5
  name: string;
6
6
  key: string;
@@ -10,6 +10,8 @@ export type AppDefinition = {
10
10
  export interface IConnectedApp {
11
11
  isConnected(): boolean;
12
12
  init(): boolean;
13
+ getSupportedOperations(): AppsOperation[];
14
+ getDefaultOperations(): AppsOperation[];
13
15
  }
14
16
  export type * from './strava/types';
15
17
  export type * from './komoot/types';
@@ -0,0 +1,48 @@
1
+ import { IExternalAppApi } from "../../../apps/base/types";
2
+ import { IncyclistService } from "../../../base/service";
3
+ import { Observer } from "../../../base/types";
4
+ import { IConnectedApp } from "../../../types";
5
+ import { Route } from "../../base/model/route";
6
+ import { IRouteList, RouteInfo } from "../../types";
7
+ import { RouteSyncFactory } from "../factory";
8
+ import { IRouteSyncProvider, RouteSyncSummary } from "../types";
9
+ interface SyncModifications<T> {
10
+ added: Array<T>;
11
+ updated: Array<Route>;
12
+ deleted: Array<string>;
13
+ }
14
+ export declare abstract class BaseSyncProvider<T, A extends IExternalAppApi, C extends IConnectedApp> extends IncyclistService implements IRouteSyncProvider {
15
+ protected lastSyncTS: number;
16
+ protected observer: Observer;
17
+ protected stopRequested: boolean;
18
+ sync(): Observer;
19
+ isConnected(): boolean;
20
+ abstract loadDetails(route: Route): Promise<Route>;
21
+ protected getOriginalId(route: Route): string;
22
+ protected loadTours(): Promise<Array<T>>;
23
+ protected checkTours(candidates: Array<T>): SyncModifications<T>;
24
+ protected stopSync(): void;
25
+ protected emitUpdates(added: T[], updated: Route[], deleted: string[]): void;
26
+ protected emitAdded(tours: Array<T>): void;
27
+ protected emitUpdated(routes: Array<Route>): void;
28
+ protected emitDeleted(routes: Array<string>): void;
29
+ protected getLastSyncTime(): Date;
30
+ protected getCreatedFilter(days?: number): Date;
31
+ protected updateLastSyncTime(): void;
32
+ protected saveLastSyncTime(): void;
33
+ protected getSyncKey(): string;
34
+ protected getUserSettings(): import("../../../settings").UserSettingsService;
35
+ protected getRouteListService(): IRouteList;
36
+ protected getRouteSyncFactory(): RouteSyncFactory;
37
+ protected getAppsService(): import("../../../apps").AppsService;
38
+ protected abstract buildRouteInfo(tour: T): RouteInfo;
39
+ protected abstract getApi(): A;
40
+ protected abstract getConnection(): C;
41
+ protected abstract getRouteSyncSummary(route: T): RouteSyncSummary;
42
+ protected abstract loadRoutesFromApi(): Promise<{
43
+ routes: Array<T>;
44
+ done: boolean;
45
+ error: boolean;
46
+ }>;
47
+ }
48
+ export {};
@@ -0,0 +1,20 @@
1
+ import { StravaApi, StravaAppConnection, StravaRoute } from "../../../apps";
2
+ import { Route } from "../../base/model/route";
3
+ import { RouteInfo } from "../../types";
4
+ import { BaseSyncProvider } from "../base/provider";
5
+ import { IRouteSyncProvider, RouteSyncSummary } from "../types";
6
+ export declare class StravaSyncProvider extends BaseSyncProvider<StravaRoute, StravaApi, StravaAppConnection> implements IRouteSyncProvider {
7
+ constructor();
8
+ loadDetails(route: Route): Promise<Route>;
9
+ protected loadRoutesFromApi(): Promise<{
10
+ routes: Array<StravaRoute>;
11
+ done: boolean;
12
+ error: boolean;
13
+ }>;
14
+ protected addRouteDetails(route: Route, gpx: string): Promise<void>;
15
+ protected getSportFilter(): string;
16
+ protected getRouteSyncSummary(route: StravaRoute): RouteSyncSummary;
17
+ protected buildRouteInfo(route: StravaRoute): RouteInfo;
18
+ protected getApi(): StravaApi;
19
+ protected getConnection(): StravaAppConnection;
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incyclist-services",
3
- "version": "1.9.23",
3
+ "version": "1.9.25",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },