incyclist-services 1.9.24 → 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.
@@ -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 {};
@@ -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
+ }
@@ -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.24",
3
+ "version": "1.9.25",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },