incyclist-services 1.9.30 → 1.9.32
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.
- package/lib/cjs/activities/upload/index.js +2 -0
- package/lib/cjs/activities/upload/komoot.js +2 -2
- package/lib/cjs/activities/upload/ridewithgps.js +158 -0
- package/lib/cjs/activities/upload/trainerday.js +216 -0
- package/lib/cjs/activities/upload/trainingpeaks.js +2 -2
- package/lib/cjs/apps/base/api/index.js +2 -0
- package/lib/cjs/apps/base/api/oauth.js +170 -0
- package/lib/cjs/apps/base/api/ridewithgps/api.js +129 -0
- package/lib/cjs/apps/base/api/ridewithgps/index.js +19 -0
- package/lib/cjs/apps/base/api/ridewithgps/types.js +18 -0
- package/lib/cjs/apps/base/api/ridewithgps/utils.js +42 -0
- package/lib/cjs/apps/base/api/trainerday/api.js +58 -0
- package/lib/cjs/apps/base/api/trainerday/index.js +18 -0
- package/lib/cjs/apps/base/api/trainerday/types.js +4 -0
- package/lib/cjs/apps/base/api/trainingpeaks/api.js +17 -133
- package/lib/cjs/apps/base/app/OAuthAppConnection.js +21 -4
- package/lib/cjs/apps/base/utils.js +34 -1
- package/lib/cjs/apps/index.js +2 -0
- package/lib/cjs/apps/ridewithgps/RideWithGpsAppConnection.js +83 -0
- package/lib/cjs/apps/ridewithgps/index.js +18 -0
- package/lib/cjs/apps/ridewithgps/types.js +2 -0
- package/lib/cjs/apps/service.js +13 -1
- package/lib/cjs/apps/trainerday/TrainerDayAppConnection.js +91 -0
- package/lib/cjs/apps/trainerday/index.js +18 -0
- package/lib/cjs/apps/trainerday/types.js +2 -0
- package/lib/cjs/coaches/coach.js +14 -6
- package/lib/cjs/devices/ride/service.js +42 -0
- package/lib/cjs/ride/base/base.js +14 -0
- package/lib/cjs/ride/route/RLVDisplayService.js +18 -4
- package/lib/cjs/routes/sync/base/provider.js +51 -9
- package/lib/cjs/routes/sync/index.js +1 -0
- package/lib/cjs/routes/sync/komoot/provider.js +1 -27
- package/lib/cjs/routes/sync/ridewithgps/provider.js +182 -0
- package/lib/cjs/routes/sync/strava/provider.js +1 -28
- package/lib/cjs/utils/base64.js +52 -0
- package/lib/cjs/utils/index.js +2 -0
- package/lib/cjs/utils/utf8.js +66 -0
- package/lib/cjs/utils/xml.js +16 -1
- package/lib/cjs/video/VideoConversion.js +3 -0
- package/lib/cjs/workouts/base/parsers/trainerday/converter.js +139 -0
- package/lib/cjs/workouts/base/parsers/trainerday/types.js +2 -0
- package/lib/cjs/workouts/calendar/sync/base/provider.js +150 -0
- package/lib/cjs/workouts/calendar/sync/base/types.js +2 -0
- package/lib/cjs/workouts/calendar/sync/index.js +1 -0
- package/lib/cjs/workouts/calendar/sync/trainerday/provider.js +142 -0
- package/lib/cjs/workouts/calendar/sync/trainingpeaks/provider.js +26 -101
- package/lib/esm/activities/upload/index.js +2 -0
- package/lib/esm/activities/upload/komoot.js +2 -2
- package/lib/esm/activities/upload/ridewithgps.js +155 -0
- package/lib/esm/activities/upload/trainerday.js +213 -0
- package/lib/esm/activities/upload/trainingpeaks.js +1 -1
- package/lib/esm/apps/base/api/index.js +2 -0
- package/lib/esm/apps/base/api/oauth.js +166 -0
- package/lib/esm/apps/base/api/ridewithgps/api.js +125 -0
- package/lib/esm/apps/base/api/ridewithgps/index.js +3 -0
- package/lib/esm/apps/base/api/ridewithgps/types.js +12 -0
- package/lib/esm/apps/base/api/ridewithgps/utils.js +34 -0
- package/lib/esm/apps/base/api/trainerday/api.js +54 -0
- package/lib/esm/apps/base/api/trainerday/index.js +2 -0
- package/lib/esm/apps/base/api/trainerday/types.js +1 -0
- package/lib/esm/apps/base/api/trainerday/utils.js +117 -0
- package/lib/esm/apps/base/api/trainingpeaks/api.js +15 -131
- package/lib/esm/apps/base/app/OAuthAppConnection.js +21 -4
- package/lib/esm/apps/base/utils.js +29 -0
- package/lib/esm/apps/index.js +2 -0
- package/lib/esm/apps/ridewithgps/RideWithGpsAppConnection.js +80 -0
- package/lib/esm/apps/ridewithgps/index.js +2 -0
- package/lib/esm/apps/ridewithgps/types.js +1 -0
- package/lib/esm/apps/service.js +13 -1
- package/lib/esm/apps/trainerday/TrainerDayAppConnection.js +88 -0
- package/lib/esm/apps/trainerday/index.js +2 -0
- package/lib/esm/apps/trainerday/types.js +1 -0
- package/lib/esm/coaches/coach.js +14 -6
- package/lib/esm/devices/ride/service.js +42 -0
- package/lib/esm/ride/base/base.js +14 -0
- package/lib/esm/ride/route/RLVDisplayService.js +18 -4
- package/lib/esm/routes/sync/base/provider.js +51 -9
- package/lib/esm/routes/sync/index.js +1 -0
- package/lib/esm/routes/sync/komoot/provider.js +1 -27
- package/lib/esm/routes/sync/ridewithgps/provider.js +178 -0
- package/lib/esm/routes/sync/strava/provider.js +1 -28
- package/lib/esm/utils/base64.js +45 -0
- package/lib/esm/utils/index.js +2 -0
- package/lib/esm/utils/utf8.js +59 -0
- package/lib/esm/utils/xml.js +14 -0
- package/lib/esm/video/VideoConversion.js +3 -0
- package/lib/esm/workouts/base/parsers/trainerday/converter.js +133 -0
- package/lib/esm/workouts/base/parsers/trainerday/types.js +1 -0
- package/lib/esm/workouts/calendar/sync/base/provider.js +147 -0
- package/lib/esm/workouts/calendar/sync/base/types.js +1 -0
- package/lib/esm/workouts/calendar/sync/index.js +1 -0
- package/lib/esm/workouts/calendar/sync/trainerday/provider.js +139 -0
- package/lib/esm/workouts/calendar/sync/trainingpeaks/provider.js +26 -101
- package/lib/types/activities/upload/index.d.ts +2 -0
- package/lib/types/activities/upload/ridewithgps.d.ts +30 -0
- package/lib/types/activities/upload/trainerday.d.ts +32 -0
- package/lib/types/activities/upload/types.d.ts +1 -0
- package/lib/types/apps/base/api/index.d.ts +2 -0
- package/lib/types/apps/base/api/oauth.d.ts +35 -0
- package/lib/types/apps/base/api/ridewithgps/api.d.ts +18 -0
- package/lib/types/apps/base/api/ridewithgps/index.d.ts +3 -0
- package/lib/types/apps/base/api/ridewithgps/types.d.ts +104 -0
- package/lib/types/apps/base/api/ridewithgps/utils.d.ts +9 -0
- package/lib/types/apps/base/api/trainerday/api.d.ts +9 -0
- package/lib/types/apps/base/api/trainerday/index.d.ts +2 -0
- package/lib/types/apps/base/api/trainerday/types.d.ts +62 -0
- package/lib/types/apps/base/api/trainerday/utils.d.ts +13 -0
- package/lib/types/apps/base/api/trainingpeaks/api.d.ts +2 -24
- package/lib/types/apps/base/api/trainingpeaks/types.d.ts +3 -13
- package/lib/types/apps/base/api/types.d.ts +21 -0
- package/lib/types/apps/base/app/OAuthAppConnection.d.ts +6 -1
- package/lib/types/apps/base/types.d.ts +1 -1
- package/lib/types/apps/base/utils.d.ts +7 -0
- package/lib/types/apps/index.d.ts +2 -0
- package/lib/types/apps/ridewithgps/RideWithGpsAppConnection.d.ts +13 -0
- package/lib/types/apps/ridewithgps/index.d.ts +2 -0
- package/lib/types/apps/ridewithgps/types.d.ts +2 -0
- package/lib/types/apps/service.d.ts +1 -0
- package/lib/types/apps/trainerday/TrainerDayAppConnection.d.ts +13 -0
- package/lib/types/apps/trainerday/index.d.ts +2 -0
- package/lib/types/apps/trainerday/types.d.ts +2 -0
- package/lib/types/apps/types.d.ts +2 -0
- package/lib/types/coaches/coach.d.ts +1 -0
- package/lib/types/devices/ride/service.d.ts +5 -1
- package/lib/types/ride/base/base.d.ts +1 -0
- package/lib/types/ride/base/types.d.ts +7 -0
- package/lib/types/ride/display/service.d.ts +1 -1
- package/lib/types/ride/route/RLVDisplayService.d.ts +3 -2
- package/lib/types/routes/sync/base/provider.d.ts +5 -1
- package/lib/types/routes/sync/index.d.ts +1 -0
- package/lib/types/routes/sync/ridewithgps/provider.d.ts +41 -0
- package/lib/types/utils/base64.d.ts +4 -0
- package/lib/types/utils/index.d.ts +2 -0
- package/lib/types/utils/utf8.d.ts +4 -0
- package/lib/types/utils/xml.d.ts +1 -0
- package/lib/types/video/VideoConversion.d.ts +1 -0
- package/lib/types/workouts/base/parsers/trainerday/converter.d.ts +7 -0
- package/lib/types/workouts/base/parsers/trainerday/types.d.ts +5 -0
- package/lib/types/workouts/calendar/sync/base/provider.d.ts +26 -0
- package/lib/types/workouts/calendar/sync/base/types.d.ts +3 -0
- package/lib/types/workouts/calendar/sync/index.d.ts +1 -0
- package/lib/types/workouts/calendar/sync/trainerday/provider.d.ts +19 -0
- package/lib/types/workouts/calendar/sync/trainingpeaks/provider.d.ts +7 -14
- package/package.json +2 -2
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RideWithGpsApi = void 0;
|
|
4
|
+
const sleep_1 = require("../../../../utils/sleep");
|
|
5
|
+
const oauth_1 = require("../oauth");
|
|
6
|
+
const types_1 = require("./types");
|
|
7
|
+
const utils_1 = require("./utils");
|
|
8
|
+
const POLL_INTERVAL_MS = 1000;
|
|
9
|
+
const MAX_POLLS = 60;
|
|
10
|
+
class RideWithGpsApi extends oauth_1.OAuthAppApiBase {
|
|
11
|
+
constructor() {
|
|
12
|
+
super('RideWithGpsApi', {
|
|
13
|
+
name: 'RideWithGPS',
|
|
14
|
+
defaultApiUrl: 'https://ridewithgps.com',
|
|
15
|
+
authCheckPath: '/api/v1/users/current.json',
|
|
16
|
+
apiUrlSetting: 'RWGPS_API',
|
|
17
|
+
authUrlSetting: 'RWGPS_AUTH_SERVER_URL'
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async getRoutes(props = {}) {
|
|
21
|
+
const params = {};
|
|
22
|
+
if (props.page !== undefined)
|
|
23
|
+
params.page = props.page;
|
|
24
|
+
if (props.pageSize !== undefined)
|
|
25
|
+
params.page_size = props.pageSize;
|
|
26
|
+
if (props.archived !== undefined)
|
|
27
|
+
params.archived = String(props.archived);
|
|
28
|
+
const response = await this.get('/api/v1/routes.json', { params });
|
|
29
|
+
if (!Array.isArray(response.data?.routes))
|
|
30
|
+
throw new Error('Unexpected response from RideWithGPS routes: expected a list of routes');
|
|
31
|
+
return { routes: response.data.routes, pagination: response.data.meta?.pagination };
|
|
32
|
+
}
|
|
33
|
+
async getCollections() {
|
|
34
|
+
const response = await this.get('/api/v1/collections.json', { params: { page_size: 100 } });
|
|
35
|
+
if (!Array.isArray(response.data?.collections))
|
|
36
|
+
throw new Error('Unexpected response from RideWithGPS collections: expected a list of collections');
|
|
37
|
+
return response.data.collections;
|
|
38
|
+
}
|
|
39
|
+
async getCollection(id) {
|
|
40
|
+
const response = await this.get(`/api/v1/collections/${id}.json`);
|
|
41
|
+
if (!response.data?.collection)
|
|
42
|
+
throw new Error('Unexpected response from RideWithGPS collection: collection is missing');
|
|
43
|
+
return response.data.collection;
|
|
44
|
+
}
|
|
45
|
+
async getRoute(id) {
|
|
46
|
+
const response = await this.get(`/api/v1/routes/${id}.json`);
|
|
47
|
+
if (!response.data?.route)
|
|
48
|
+
throw new Error('Unexpected response from RideWithGPS route: route is missing');
|
|
49
|
+
return response.data.route;
|
|
50
|
+
}
|
|
51
|
+
async getRouteAsGPX(id) {
|
|
52
|
+
const response = await this.get(`/api/v1/routes/${id}.gpx`, { responseType: 'text' });
|
|
53
|
+
if (typeof response.data !== 'string' || response.data.length === 0)
|
|
54
|
+
throw new Error('Unexpected response from RideWithGPS route: no GPX content');
|
|
55
|
+
return response.data;
|
|
56
|
+
}
|
|
57
|
+
async uploadActivity(props) {
|
|
58
|
+
await this.verifyAuthentication();
|
|
59
|
+
const task = await this.createUpload(props);
|
|
60
|
+
const finished = await this.waitForTask(task);
|
|
61
|
+
if (finished.status !== 'completed')
|
|
62
|
+
throw (0, utils_1.getTaskFailure)(finished);
|
|
63
|
+
const result = (0, utils_1.getUploadResult)(finished);
|
|
64
|
+
if (result.tripId && !result.duplicate && props.activityType)
|
|
65
|
+
await this.setActivityType(result.tripId, props.activityType);
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
async createUpload(props) {
|
|
69
|
+
const fields = { file: { type: 'file', fileName: props.fileName } };
|
|
70
|
+
if (props.name)
|
|
71
|
+
fields.name = props.name;
|
|
72
|
+
if (props.description)
|
|
73
|
+
fields.description = props.description;
|
|
74
|
+
this.logger.logEvent({ message: 'RideWithGPS upload' });
|
|
75
|
+
try {
|
|
76
|
+
const form = await this.createForm('/api/v1/trips.json', fields, { headers: this.getAuthHeaders() });
|
|
77
|
+
const response = await this.postForm(form);
|
|
78
|
+
if (!response.data?.task)
|
|
79
|
+
throw new Error('Unexpected response from RideWithGPS upload: task is missing');
|
|
80
|
+
return response.data.task;
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
await this.checkRevoked(err);
|
|
84
|
+
throw this.toUploadError(err);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
toUploadError(err) {
|
|
88
|
+
const mapped = this.mapUploadRejection(err);
|
|
89
|
+
return err?.response?.status === 401 ? new types_1.RideWithGpsAuthError(mapped.message) : mapped;
|
|
90
|
+
}
|
|
91
|
+
async getTask(id) {
|
|
92
|
+
const response = await this.request('get', `/api/v1/tasks/${id}.json`, undefined, undefined, { checkRevoked: false });
|
|
93
|
+
if (!response.data?.task)
|
|
94
|
+
throw new Error('Unexpected response from RideWithGPS task: task is missing');
|
|
95
|
+
return response.data.task;
|
|
96
|
+
}
|
|
97
|
+
async waitForTask(initial) {
|
|
98
|
+
let task = initial;
|
|
99
|
+
for (let polls = 0; polls < MAX_POLLS; polls++) {
|
|
100
|
+
if (task.status !== 'pending')
|
|
101
|
+
return task;
|
|
102
|
+
await (0, sleep_1.sleep)(POLL_INTERVAL_MS);
|
|
103
|
+
task = await this.pollTask(task.id);
|
|
104
|
+
}
|
|
105
|
+
if (task.status === 'pending')
|
|
106
|
+
throw new types_1.RideWithGpsTimeoutError();
|
|
107
|
+
return task;
|
|
108
|
+
}
|
|
109
|
+
async pollTask(id) {
|
|
110
|
+
try {
|
|
111
|
+
return await this.getTask(id);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
throw new types_1.RideWithGpsTimeoutError('Could not read the status of the RideWithGPS upload: ' + err.message);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async setActivityType(tripId, activityType) {
|
|
118
|
+
try {
|
|
119
|
+
await this.request('put', `/api/v1/trips/${tripId}.json`, { trip: { activity_type: activityType } }, undefined, { checkRevoked: false });
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
this.logger.logEvent({ message: 'RideWithGPS set activity type failed', tripId, activityType, error: err.message });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
getExpiration() {
|
|
126
|
+
return new Date(8.64e15);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
exports.RideWithGpsApi = RideWithGpsApi;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./api"), exports);
|
|
18
|
+
__exportStar(require("./types"), exports);
|
|
19
|
+
__exportStar(require("./utils"), exports);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RideWithGpsAuthError = exports.RideWithGpsTimeoutError = exports.RideWithGpsTimeDataMissingError = void 0;
|
|
4
|
+
class RideWithGpsTimeDataMissingError extends Error {
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message ?? 'Upload rejected by RideWithGPS: the file has no time data');
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
exports.RideWithGpsTimeDataMissingError = RideWithGpsTimeDataMissingError;
|
|
10
|
+
class RideWithGpsTimeoutError extends Error {
|
|
11
|
+
constructor(message) {
|
|
12
|
+
super(message ?? 'RideWithGPS did not finish processing the upload in time');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.RideWithGpsTimeoutError = RideWithGpsTimeoutError;
|
|
16
|
+
class RideWithGpsAuthError extends Error {
|
|
17
|
+
}
|
|
18
|
+
exports.RideWithGpsAuthError = RideWithGpsAuthError;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUploadResult = exports.getTaskFailure = exports.isOwnActiveRoute = exports.isSyncedCollection = exports.isRoadCyclingRoute = exports.UNPAVED_THRESHOLD_PCT = void 0;
|
|
4
|
+
const types_1 = require("./types");
|
|
5
|
+
exports.UNPAVED_THRESHOLD_PCT = 50;
|
|
6
|
+
const OFFROAD_TYPES = new Set(['cycling:gravel', 'cycling:mountain', 'cycling:cyclocross']);
|
|
7
|
+
const OTHER_SPORTS = ['walking:', 'running:', 'driving:', 'motorcycling:', 'swimming:', 'snow:'];
|
|
8
|
+
const isClearlyNotRoad = (type) => OFFROAD_TYPES.has(type) || OTHER_SPORTS.some(sport => type.startsWith(sport));
|
|
9
|
+
const isRoadCyclingRoute = (route) => {
|
|
10
|
+
const types = route.activity_types;
|
|
11
|
+
if (Array.isArray(types) && types.length > 0)
|
|
12
|
+
return !types.every(isClearlyNotRoad);
|
|
13
|
+
return !(typeof route.unpaved_pct === 'number' && route.unpaved_pct >= exports.UNPAVED_THRESHOLD_PCT);
|
|
14
|
+
};
|
|
15
|
+
exports.isRoadCyclingRoute = isRoadCyclingRoute;
|
|
16
|
+
const SYNCED_COLLECTIONS = new Set(['pinned', 'bucket list']);
|
|
17
|
+
const isSyncedCollection = (collection) => {
|
|
18
|
+
const name = (collection.name ?? '').toLowerCase().replaceAll(/[{}_]/g, ' ').trim().replaceAll(/\s+/g, ' ');
|
|
19
|
+
return SYNCED_COLLECTIONS.has(name);
|
|
20
|
+
};
|
|
21
|
+
exports.isSyncedCollection = isSyncedCollection;
|
|
22
|
+
const isOwnActiveRoute = (route) => route.archived !== true && route.archived !== null;
|
|
23
|
+
exports.isOwnActiveRoute = isOwnActiveRoute;
|
|
24
|
+
const describeError = (error) => `Upload rejected by RideWithGPS: ${error.code}${error.message ? ' (' + error.message + ')' : ''}`;
|
|
25
|
+
const getTaskFailure = (task) => task.errors?.length ? new Error(describeError(task.errors[0])) : new Error(`RideWithGPS upload ended with status ${task.status}`);
|
|
26
|
+
exports.getTaskFailure = getTaskFailure;
|
|
27
|
+
const getUploadResult = (task) => {
|
|
28
|
+
const created = task.items?.find(item => item.item_type === 'trip') ?? task.items?.[0];
|
|
29
|
+
if (created)
|
|
30
|
+
return { tripId: String(created.item_id) };
|
|
31
|
+
const errors = task.errors ?? [];
|
|
32
|
+
const duplicate = errors.find(e => e.code === 'duplicate');
|
|
33
|
+
if (duplicate) {
|
|
34
|
+
const tripId = duplicate.item_id === undefined || duplicate.item_id === null ? undefined : String(duplicate.item_id);
|
|
35
|
+
return { tripId, duplicate: true };
|
|
36
|
+
}
|
|
37
|
+
const timeMissing = errors.find(e => e.code === 'time_data_missing');
|
|
38
|
+
if (timeMissing)
|
|
39
|
+
throw new types_1.RideWithGpsTimeDataMissingError(describeError(timeMissing));
|
|
40
|
+
throw new Error(errors.length > 0 ? describeError(errors[0]) : 'RideWithGPS did not create a trip');
|
|
41
|
+
};
|
|
42
|
+
exports.getUploadResult = getUploadResult;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TrainerDayApi = void 0;
|
|
4
|
+
const xml_1 = require("../../../../utils/xml");
|
|
5
|
+
const oauth_1 = require("../oauth");
|
|
6
|
+
const base64_1 = require("../../../../utils/base64");
|
|
7
|
+
const utf8_1 = require("../../../../utils/utf8");
|
|
8
|
+
const utils_1 = require("../../utils");
|
|
9
|
+
const types_1 = require("./types");
|
|
10
|
+
class TrainerDayApi extends oauth_1.OAuthAppApiBase {
|
|
11
|
+
constructor() {
|
|
12
|
+
super('TrainerDayApi', {
|
|
13
|
+
name: 'TrainerDay',
|
|
14
|
+
refreshPath: '/trainerday/refresh',
|
|
15
|
+
defaultApiUrl: 'https://api.trainerday.com',
|
|
16
|
+
apiUrlSetting: 'TRAINERDAY_API',
|
|
17
|
+
authUrlSetting: 'TRAINERDAY_AUTH_SERVER_URL'
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async getCalendar(startDate, endDate) {
|
|
21
|
+
const params = { startDate: (0, utils_1.formatDay)(startDate), endDate: (0, utils_1.formatDay)(endDate) };
|
|
22
|
+
const response = await this.get('/api/v2/calendar', { params });
|
|
23
|
+
if (!Array.isArray(response.data))
|
|
24
|
+
throw new Error('Unexpected response from TrainerDay calendar: expected an array');
|
|
25
|
+
return response.data;
|
|
26
|
+
}
|
|
27
|
+
async uploadActivity(props) {
|
|
28
|
+
const { name, dataType, externalId, sportType } = props;
|
|
29
|
+
const data = this.prepareData(props);
|
|
30
|
+
this.logger.logEvent({ message: 'TrainerDay upload', format: dataType, bytes: (0, base64_1.base64Size)(data) });
|
|
31
|
+
const body = { name, dataType, data, externalId, sportType };
|
|
32
|
+
let response;
|
|
33
|
+
try {
|
|
34
|
+
response = await this.request('post', '/api/v1/activities/upload', body);
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
throw this.mapUploadRejection(err);
|
|
38
|
+
}
|
|
39
|
+
if (response.data?.duplicate === true) {
|
|
40
|
+
const activityId = response.data.id ?? response.data.activityId;
|
|
41
|
+
this.logger.logEvent({ message: 'TrainerDay upload duplicate', activityId });
|
|
42
|
+
return { activityId, duplicate: true };
|
|
43
|
+
}
|
|
44
|
+
return { activityId: response.data?.activityId };
|
|
45
|
+
}
|
|
46
|
+
prepareData(props) {
|
|
47
|
+
const isXml = props.dataType === 'tcx' || props.dataType === 'gpx';
|
|
48
|
+
const bytes = typeof props.data === 'string' ? undefined : props.data;
|
|
49
|
+
if (!isXml)
|
|
50
|
+
return bytes ? (0, base64_1.toBase64)(bytes) : props.data;
|
|
51
|
+
const xml = (0, utf8_1.utf8Decode)(bytes ?? (0, base64_1.fromBase64)(props.data));
|
|
52
|
+
return (0, base64_1.toBase64)((0, utf8_1.utf8Encode)((0, xml_1.trimXmlTextNodes)(xml)));
|
|
53
|
+
}
|
|
54
|
+
getExpiration(data) {
|
|
55
|
+
return (0, utils_1.getTokenExpiration)(data, types_1.DEFAULT_TOKEN_LIFETIME_MS);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
exports.TrainerDayApi = TrainerDayApi;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./api"), exports);
|
|
18
|
+
__exportStar(require("./types"), exports);
|
|
@@ -1,46 +1,30 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TrainingPeaksApi = void 0;
|
|
4
|
-
const gd_eventlog_1 = require("gd-eventlog");
|
|
5
|
-
const observer_1 = require("../../../../base/types/observer");
|
|
6
|
-
const valid_1 = require("../../../../utils/valid");
|
|
7
|
-
const base_1 = require("../base");
|
|
8
4
|
const sleep_1 = require("../../../../utils/sleep");
|
|
9
|
-
const
|
|
5
|
+
const xml_1 = require("../../../../utils/xml");
|
|
6
|
+
const utils_1 = require("../../utils");
|
|
7
|
+
const oauth_1 = require("../oauth");
|
|
8
|
+
const base64_1 = require("../../../../utils/base64");
|
|
10
9
|
const types_1 = require("./types");
|
|
11
|
-
const API_BASE_URL = 'https://api.trainingpeaks.com';
|
|
12
|
-
const AUTH_SERVER_URL = 'https://auth.incyclist.com';
|
|
13
10
|
const APP_URL = 'https://app.trainingpeaks.com';
|
|
14
11
|
const SANDBOX_APP_URL = 'https://app.sandbox.trainingpeaks.com';
|
|
15
12
|
const UPLOAD_CLIENT = 'Incyclist';
|
|
16
13
|
const MAX_WORKOUT_RANGE_DAYS = 45;
|
|
17
14
|
const UPLOAD_POLL_INTERVAL = 2000;
|
|
18
15
|
const UPLOAD_TIMEOUT = 60000;
|
|
19
|
-
const MAX_ERROR_DETAIL = 500;
|
|
20
16
|
const OFFSET_STEP_MS = 15 * 60 * 1000;
|
|
21
17
|
const MAX_OFFSET_MS = 14 * 60 * 60 * 1000;
|
|
22
18
|
const MATCH_TOLERANCE_MS = 1000;
|
|
23
|
-
class TrainingPeaksApi extends
|
|
24
|
-
config;
|
|
25
|
-
logger;
|
|
26
|
-
observer;
|
|
19
|
+
class TrainingPeaksApi extends oauth_1.OAuthAppApiBase {
|
|
27
20
|
constructor() {
|
|
28
|
-
super(
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
return this.observer;
|
|
36
|
-
}
|
|
37
|
-
update(config) {
|
|
38
|
-
if (!this.config)
|
|
39
|
-
throw new Error('update not allowed before init');
|
|
40
|
-
this.config = { ...this.config, ...config };
|
|
41
|
-
}
|
|
42
|
-
isAuthenticated() {
|
|
43
|
-
return (0, valid_1.valid)(this.config?.accessToken);
|
|
21
|
+
super('TrainingPeaksApi', {
|
|
22
|
+
name: 'TrainingPeaks',
|
|
23
|
+
refreshPath: '/trainingpeaks/refresh',
|
|
24
|
+
defaultApiUrl: 'https://api.trainingpeaks.com',
|
|
25
|
+
apiUrlSetting: 'TP_API',
|
|
26
|
+
authUrlSetting: 'TP_AUTH_SERVER_URL'
|
|
27
|
+
});
|
|
44
28
|
}
|
|
45
29
|
getCalendarUrl() {
|
|
46
30
|
const isSandbox = this.getBaseUrl().toLowerCase().includes('sandbox');
|
|
@@ -50,7 +34,7 @@ class TrainingPeaksApi extends base_1.AppApiBase {
|
|
|
50
34
|
const days = (end.valueOf() - start.valueOf()) / 86400000;
|
|
51
35
|
if (days < 0 || days > MAX_WORKOUT_RANGE_DAYS)
|
|
52
36
|
throw new Error(`invalid range: start and end must not be more than ${MAX_WORKOUT_RANGE_DAYS} days apart`);
|
|
53
|
-
const response = await this.get(`/v2/workouts/${
|
|
37
|
+
const response = await this.get(`/v2/workouts/${(0, utils_1.formatDay)(start)}/${(0, utils_1.formatDay)(end)}`);
|
|
54
38
|
return (response.data ?? []);
|
|
55
39
|
}
|
|
56
40
|
async findWorkout(start) {
|
|
@@ -81,12 +65,12 @@ class TrainingPeaksApi extends base_1.AppApiBase {
|
|
|
81
65
|
return response.data;
|
|
82
66
|
}
|
|
83
67
|
async upload(props) {
|
|
84
|
-
if (!(0,
|
|
68
|
+
if (!(0, base64_1.isBase64)(props.data))
|
|
85
69
|
throw new Error('Upload failed, reason: data is not base64 encoded');
|
|
86
70
|
const data = this.prepareData(props);
|
|
87
71
|
this.logger.logEvent({
|
|
88
72
|
message: 'TrainingPeaks upload', format: props.fileName.split('.').at(-1)?.toLowerCase(),
|
|
89
|
-
bytes:
|
|
73
|
+
bytes: (0, base64_1.base64Size)(props.data), bytesSent: (0, base64_1.base64Size)(data)
|
|
90
74
|
});
|
|
91
75
|
const request = {
|
|
92
76
|
UploadClient: UPLOAD_CLIENT,
|
|
@@ -104,24 +88,7 @@ class TrainingPeaksApi extends base_1.AppApiBase {
|
|
|
104
88
|
if (!props.fileName.toLowerCase().endsWith('.tcx'))
|
|
105
89
|
return props.data;
|
|
106
90
|
const xml = Buffer.from(props.data, 'base64').toString('utf-8');
|
|
107
|
-
return Buffer.from((0,
|
|
108
|
-
}
|
|
109
|
-
async request(method, url, data, config) {
|
|
110
|
-
await this.verifyAuthentication();
|
|
111
|
-
const request = {
|
|
112
|
-
method,
|
|
113
|
-
url: this.getBaseUrl() + url,
|
|
114
|
-
data,
|
|
115
|
-
headers: {
|
|
116
|
-
Authorization: 'Bearer ' + this.config.accessToken
|
|
117
|
-
},
|
|
118
|
-
validateStatus: (status) => status >= 200 && status < 300,
|
|
119
|
-
...config
|
|
120
|
-
};
|
|
121
|
-
return await this.getApi().request(request);
|
|
122
|
-
}
|
|
123
|
-
async get(url, config) {
|
|
124
|
-
return await this.request('get', url, undefined, config);
|
|
91
|
+
return Buffer.from((0, xml_1.trimXmlTextNodes)(xml), 'utf-8').toString('base64');
|
|
125
92
|
}
|
|
126
93
|
async createUpload(request) {
|
|
127
94
|
let response;
|
|
@@ -160,69 +127,7 @@ class TrainingPeaksApi extends base_1.AppApiBase {
|
|
|
160
127
|
return new types_1.TrainingPeaksDuplicateError();
|
|
161
128
|
if (status === 415)
|
|
162
129
|
return new Error('File format is not supported by TrainingPeaks');
|
|
163
|
-
|
|
164
|
-
const detail = this.getErrorDetail(err.response.data);
|
|
165
|
-
return new Error(`Upload rejected by TrainingPeaks (HTTP ${status})${detail ? ': ' + detail : ''}`);
|
|
166
|
-
}
|
|
167
|
-
return err;
|
|
168
|
-
}
|
|
169
|
-
getErrorDetail(data) {
|
|
170
|
-
if (data === undefined || data === null || data === '')
|
|
171
|
-
return undefined;
|
|
172
|
-
const text = typeof data === 'string' ? data : JSON.stringify(data);
|
|
173
|
-
return text.length > MAX_ERROR_DETAIL ? text.substring(0, MAX_ERROR_DETAIL) + '...' : text;
|
|
174
|
-
}
|
|
175
|
-
getBase64Size(base64) {
|
|
176
|
-
const padding = base64.endsWith('==') ? 2 : Number(base64.endsWith('='));
|
|
177
|
-
return Math.floor(base64.length * 3 / 4) - padding;
|
|
178
|
-
}
|
|
179
|
-
formatDay(date) {
|
|
180
|
-
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
181
|
-
const day = String(date.getDate()).padStart(2, '0');
|
|
182
|
-
return `${date.getFullYear()}-${month}-${day}`;
|
|
183
|
-
}
|
|
184
|
-
async verifyAuthentication() {
|
|
185
|
-
if (!this.isAuthenticated())
|
|
186
|
-
throw new Error('not authenticated');
|
|
187
|
-
await this.verifyToken();
|
|
188
|
-
}
|
|
189
|
-
async verifyToken() {
|
|
190
|
-
if (this.isTokenStillValid())
|
|
191
|
-
return;
|
|
192
|
-
try {
|
|
193
|
-
await this.refreshToken();
|
|
194
|
-
}
|
|
195
|
-
catch {
|
|
196
|
-
throw new Error('token refresh failed');
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
isTokenStillValid() {
|
|
200
|
-
const expiration = this.config?.expiration;
|
|
201
|
-
if (!expiration)
|
|
202
|
-
return false;
|
|
203
|
-
return Date.now() < expiration.valueOf();
|
|
204
|
-
}
|
|
205
|
-
async refreshToken() {
|
|
206
|
-
this.logger.logEvent({ message: 'TrainingPeaks refresh token start' });
|
|
207
|
-
const url = this.getAuthServerUrl() + '/trainingpeaks/refresh';
|
|
208
|
-
try {
|
|
209
|
-
const response = await this.getApi().request({
|
|
210
|
-
method: 'post',
|
|
211
|
-
url,
|
|
212
|
-
data: { refresh_token: this.config.refreshToken }
|
|
213
|
-
});
|
|
214
|
-
const data = response.data;
|
|
215
|
-
this.config.accessToken = data.access_token;
|
|
216
|
-
this.config.refreshToken = data.refresh_token;
|
|
217
|
-
this.config.expiration = this.getExpiration(data);
|
|
218
|
-
this.logger.logEvent({ message: 'TrainingPeaks refresh token result', status: 'success' });
|
|
219
|
-
this.observer.emit('token.updated', this.config);
|
|
220
|
-
}
|
|
221
|
-
catch (err) {
|
|
222
|
-
const error = err.response ? `HTTP error ${err.response.status}: ${err.response.statusText}, url:${url}` : err.message;
|
|
223
|
-
this.logger.logEvent({ message: 'TrainingPeaks refresh token result', status: 'error', error });
|
|
224
|
-
throw err;
|
|
225
|
-
}
|
|
130
|
+
return this.mapUploadRejection(err);
|
|
226
131
|
}
|
|
227
132
|
getExpiration(data) {
|
|
228
133
|
const expiresIn = Number(data.expires_in);
|
|
@@ -230,26 +135,5 @@ class TrainingPeaksApi extends base_1.AppApiBase {
|
|
|
230
135
|
return new Date(Date.now() + expiresIn * 1000);
|
|
231
136
|
return new Date(Number(data.expiration));
|
|
232
137
|
}
|
|
233
|
-
getAuthServerUrl() {
|
|
234
|
-
try {
|
|
235
|
-
const TP_AUTH_SERVER_URL = this.getUserSettings().get('TP_AUTH_SERVER_URL', null);
|
|
236
|
-
const oauthUrl = this.getUserSettings().get('oauthUrl', null);
|
|
237
|
-
return TP_AUTH_SERVER_URL ?? oauthUrl ?? AUTH_SERVER_URL;
|
|
238
|
-
}
|
|
239
|
-
catch {
|
|
240
|
-
return AUTH_SERVER_URL;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
getBaseUrl() {
|
|
244
|
-
try {
|
|
245
|
-
return this.getUserSettings().get('TP_API', API_BASE_URL);
|
|
246
|
-
}
|
|
247
|
-
catch {
|
|
248
|
-
return API_BASE_URL;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
getApi() {
|
|
252
|
-
return super.getApi(true);
|
|
253
|
-
}
|
|
254
138
|
}
|
|
255
139
|
exports.TrainingPeaksApi = TrainingPeaksApi;
|
|
@@ -9,6 +9,10 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
|
|
|
9
9
|
this.logEvent({ message: `Connect with ${this.appName}` });
|
|
10
10
|
try {
|
|
11
11
|
const config = this.createConfig(credentials);
|
|
12
|
+
if (!(0, valid_1.valid)(config?.accessToken)) {
|
|
13
|
+
this.logEvent({ message: `Connect with ${this.appName} failed`, reason: 'no access token' });
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
12
16
|
if (this.isConnected()) {
|
|
13
17
|
this.getApi().update(config);
|
|
14
18
|
}
|
|
@@ -41,7 +45,7 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
|
|
|
41
45
|
if (!this.isInitialized) {
|
|
42
46
|
this.init();
|
|
43
47
|
}
|
|
44
|
-
return (0, valid_1.valid)(this.config);
|
|
48
|
+
return (0, valid_1.valid)(this.config) && (0, valid_1.valid)(this.config.accessToken);
|
|
45
49
|
}
|
|
46
50
|
getCredentials() {
|
|
47
51
|
try {
|
|
@@ -63,8 +67,9 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
|
|
|
63
67
|
try {
|
|
64
68
|
const auth = this.getCredentials();
|
|
65
69
|
this.logEvent({ message: `${this.appName} init done`, hasCredentials: Boolean(auth) });
|
|
66
|
-
|
|
67
|
-
|
|
70
|
+
const config = auth ? this.createConfig(auth) : undefined;
|
|
71
|
+
if ((0, valid_1.valid)(config?.accessToken)) {
|
|
72
|
+
this.config = config;
|
|
68
73
|
this.initApi(this.config);
|
|
69
74
|
}
|
|
70
75
|
return true;
|
|
@@ -100,7 +105,19 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
|
|
|
100
105
|
}
|
|
101
106
|
initApi(config) {
|
|
102
107
|
const observer = this.getApi().init(config);
|
|
103
|
-
|
|
108
|
+
if (this.apiListeners) {
|
|
109
|
+
this.apiListeners.observer.off('token.updated', this.apiListeners.onToken);
|
|
110
|
+
this.apiListeners.observer.off('auth.failed', this.apiListeners.onFailed);
|
|
111
|
+
}
|
|
112
|
+
const onToken = (updated) => { this.updateConfig(updated); };
|
|
113
|
+
const onFailed = () => {
|
|
114
|
+
this.logEvent({ message: `${this.appName} authentication failed, credentials removed (reconnect required)` });
|
|
115
|
+
this.disconnect();
|
|
116
|
+
this.emit('auth.failed');
|
|
117
|
+
};
|
|
118
|
+
observer.on('token.updated', onToken);
|
|
119
|
+
observer.on('auth.failed', onFailed);
|
|
120
|
+
this.apiListeners = { observer, onToken, onFailed };
|
|
104
121
|
}
|
|
105
122
|
}
|
|
106
123
|
exports.OAuthAppConnection = OAuthAppConnection;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.parseExpiration = void 0;
|
|
3
|
+
exports.formatDay = exports.getErrorDetail = exports.ensureExpiration = exports.getTokenExpiration = exports.parseExpiration = void 0;
|
|
4
4
|
const MAX_EPOCH_SECONDS = 1e11;
|
|
5
5
|
const parseExpiration = (expiration) => {
|
|
6
6
|
if (expiration === undefined || expiration === null || expiration === '')
|
|
@@ -17,3 +17,36 @@ const parseExpiration = (expiration) => {
|
|
|
17
17
|
return Number.isNaN(date.valueOf()) ? undefined : date;
|
|
18
18
|
};
|
|
19
19
|
exports.parseExpiration = parseExpiration;
|
|
20
|
+
const isValidDate = (date) => date instanceof Date && !Number.isNaN(date.valueOf());
|
|
21
|
+
const toFiniteNumber = (value) => {
|
|
22
|
+
if (value === undefined || value === null || value === '')
|
|
23
|
+
return undefined;
|
|
24
|
+
const num = Number(value);
|
|
25
|
+
return Number.isFinite(num) ? num : undefined;
|
|
26
|
+
};
|
|
27
|
+
const getTokenExpiration = (data, defaultLifetimeMs) => {
|
|
28
|
+
const expiresIn = toFiniteNumber(data?.expires_in);
|
|
29
|
+
if (expiresIn !== undefined)
|
|
30
|
+
return new Date(Date.now() + expiresIn * 1000);
|
|
31
|
+
const expiration = (0, exports.parseExpiration)(data?.expiration);
|
|
32
|
+
return expiration ?? new Date(Date.now() + defaultLifetimeMs);
|
|
33
|
+
};
|
|
34
|
+
exports.getTokenExpiration = getTokenExpiration;
|
|
35
|
+
const ensureExpiration = (expiration, defaultLifetimeMs) => isValidDate(expiration) ? expiration : new Date(Date.now() + defaultLifetimeMs);
|
|
36
|
+
exports.ensureExpiration = ensureExpiration;
|
|
37
|
+
const MAX_ERROR_DETAIL = 500;
|
|
38
|
+
const getErrorDetail = (data) => {
|
|
39
|
+
if (data === undefined || data === null || data === '')
|
|
40
|
+
return undefined;
|
|
41
|
+
const text = typeof data === 'string' ? data : JSON.stringify(data);
|
|
42
|
+
return text.length > MAX_ERROR_DETAIL ? text.substring(0, MAX_ERROR_DETAIL) + '...' : text;
|
|
43
|
+
};
|
|
44
|
+
exports.getErrorDetail = getErrorDetail;
|
|
45
|
+
const formatDay = (day) => {
|
|
46
|
+
if (typeof day === 'string')
|
|
47
|
+
return day;
|
|
48
|
+
const month = String(day.getMonth() + 1).padStart(2, '0');
|
|
49
|
+
const date = String(day.getDate()).padStart(2, '0');
|
|
50
|
+
return `${day.getFullYear()}-${month}-${date}`;
|
|
51
|
+
};
|
|
52
|
+
exports.formatDay = formatDay;
|
package/lib/cjs/apps/index.js
CHANGED
|
@@ -19,3 +19,5 @@ __exportStar(require("./googleMaps"), exports);
|
|
|
19
19
|
__exportStar(require("./service"), exports);
|
|
20
20
|
__exportStar(require("./strava"), exports);
|
|
21
21
|
__exportStar(require("./trainingpeaks"), exports);
|
|
22
|
+
__exportStar(require("./trainerday"), exports);
|
|
23
|
+
__exportStar(require("./ridewithgps"), exports);
|