incyclist-services 1.9.26 → 1.9.28
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 +1 -0
- package/lib/cjs/activities/upload/trainingpeaks.js +220 -0
- package/lib/cjs/api/rest/api.js +21 -1
- package/lib/cjs/apps/base/api/index.js +1 -0
- package/lib/cjs/apps/base/api/trainingpeaks/api.js +255 -0
- package/lib/cjs/apps/base/api/trainingpeaks/index.js +18 -0
- package/lib/cjs/apps/base/api/trainingpeaks/types.js +10 -0
- package/lib/cjs/apps/base/api/trainingpeaks/utils.js +20 -0
- package/lib/cjs/apps/base/app/ConnectedAppService.js +116 -0
- package/lib/cjs/apps/base/app/OAuthAppConnection.js +106 -0
- package/lib/cjs/apps/base/app/index.js +14 -112
- package/lib/cjs/apps/base/utils.js +19 -0
- package/lib/cjs/apps/index.js +1 -0
- package/lib/cjs/apps/service.js +37 -17
- package/lib/cjs/apps/strava/StravaAppConnection.js +3 -2
- package/lib/cjs/apps/trainingpeaks/TrainingPeaksAppConnection.js +91 -0
- package/lib/cjs/apps/trainingpeaks/index.js +18 -0
- package/lib/cjs/apps/trainingpeaks/types.js +2 -0
- package/lib/cjs/routes/library/service.js +1 -1
- package/lib/cjs/workouts/calendar/sync/index.js +1 -0
- package/lib/cjs/workouts/calendar/sync/trainingpeaks/provider.js +254 -0
- package/lib/cjs/workouts/index.js +1 -0
- package/lib/cjs/workouts/list/service.js +0 -16
- package/lib/cjs/workouts/page/base/service.js +332 -0
- package/lib/cjs/workouts/page/base/types.js +2 -0
- package/lib/cjs/workouts/page/desktop/service.js +443 -0
- package/lib/cjs/workouts/page/desktop/types.js +2 -0
- package/lib/cjs/workouts/page/index.js +17 -15
- package/lib/cjs/workouts/page/mobile/service.js +256 -0
- package/lib/cjs/workouts/page/mobile/types.js +2 -0
- package/lib/cjs/workouts/prompt/index.js +18 -0
- package/lib/cjs/workouts/prompt/service.js +132 -0
- package/lib/cjs/workouts/prompt/types.js +2 -0
- package/lib/esm/activities/upload/index.js +1 -0
- package/lib/esm/activities/upload/trainingpeaks.js +217 -0
- package/lib/esm/api/rest/api.js +21 -1
- package/lib/esm/apps/base/api/index.js +1 -0
- package/lib/esm/apps/base/api/trainingpeaks/api.js +251 -0
- package/lib/esm/apps/base/api/trainingpeaks/index.js +2 -0
- package/lib/esm/apps/base/api/trainingpeaks/types.js +6 -0
- package/lib/esm/apps/base/api/trainingpeaks/utils.js +15 -0
- package/lib/esm/apps/base/app/ConnectedAppService.js +113 -0
- package/lib/esm/apps/base/app/OAuthAppConnection.js +102 -0
- package/lib/esm/apps/base/app/index.js +2 -113
- package/lib/esm/apps/base/utils.js +15 -0
- package/lib/esm/apps/index.js +1 -0
- package/lib/esm/apps/service.js +37 -17
- package/lib/esm/apps/strava/StravaAppConnection.js +3 -2
- package/lib/esm/apps/trainingpeaks/TrainingPeaksAppConnection.js +88 -0
- package/lib/esm/apps/trainingpeaks/index.js +2 -0
- package/lib/esm/apps/trainingpeaks/types.js +1 -0
- package/lib/esm/routes/library/service.js +1 -1
- package/lib/esm/workouts/calendar/sync/index.js +1 -0
- package/lib/esm/workouts/calendar/sync/trainingpeaks/provider.js +251 -0
- package/lib/esm/workouts/index.js +1 -0
- package/lib/esm/workouts/list/service.js +0 -16
- package/lib/esm/workouts/page/base/service.js +329 -0
- package/lib/esm/workouts/page/base/types.js +1 -0
- package/lib/esm/workouts/page/desktop/service.js +440 -0
- package/lib/esm/workouts/page/desktop/types.js +1 -0
- package/lib/esm/workouts/page/index.js +12 -1
- package/lib/esm/workouts/page/mobile/service.js +253 -0
- package/lib/esm/workouts/page/mobile/types.js +1 -0
- package/lib/esm/workouts/prompt/index.js +2 -0
- package/lib/esm/workouts/prompt/service.js +128 -0
- package/lib/esm/workouts/prompt/types.js +1 -0
- package/lib/types/activities/upload/index.d.ts +1 -0
- package/lib/types/activities/upload/trainingpeaks.d.ts +31 -0
- package/lib/types/api/rest/api.d.ts +1 -0
- package/lib/types/apps/base/api/index.d.ts +1 -0
- package/lib/types/apps/base/api/trainingpeaks/api.d.ts +39 -0
- package/lib/types/apps/base/api/trainingpeaks/index.d.ts +2 -0
- package/lib/types/apps/base/api/trainingpeaks/types.d.ts +56 -0
- package/lib/types/apps/base/api/trainingpeaks/utils.d.ts +2 -0
- package/lib/types/apps/base/app/ConnectedAppService.d.ts +23 -0
- package/lib/types/apps/base/app/OAuthAppConnection.d.ts +32 -0
- package/lib/types/apps/base/app/index.d.ts +2 -23
- package/lib/types/apps/base/index.d.ts +1 -0
- package/lib/types/apps/base/types.d.ts +6 -0
- package/lib/types/apps/base/utils.d.ts +1 -0
- package/lib/types/apps/index.d.ts +1 -0
- package/lib/types/apps/intervals/types.d.ts +2 -6
- package/lib/types/apps/service.d.ts +3 -2
- package/lib/types/apps/strava/types.d.ts +2 -6
- package/lib/types/apps/trainingpeaks/TrainingPeaksAppConnection.d.ts +13 -0
- package/lib/types/apps/trainingpeaks/index.d.ts +2 -0
- package/lib/types/apps/trainingpeaks/types.d.ts +2 -0
- package/lib/types/apps/types.d.ts +1 -1
- package/lib/types/workouts/calendar/sync/index.d.ts +1 -0
- package/lib/types/workouts/calendar/sync/trainingpeaks/provider.d.ts +31 -0
- package/lib/types/workouts/index.d.ts +1 -0
- package/lib/types/workouts/list/service.d.ts +0 -1
- package/lib/types/workouts/page/base/service.d.ts +41 -0
- package/lib/types/workouts/page/base/types.d.ts +37 -0
- package/lib/types/workouts/page/desktop/service.d.ts +61 -0
- package/lib/types/workouts/page/desktop/types.d.ts +42 -0
- package/lib/types/workouts/page/index.d.ts +6 -1
- package/lib/types/workouts/page/mobile/service.d.ts +31 -0
- package/lib/types/workouts/page/mobile/types.d.ts +66 -0
- package/lib/types/workouts/page/types.d.ts +3 -99
- package/lib/types/workouts/prompt/index.d.ts +2 -0
- package/lib/types/workouts/prompt/service.d.ts +17 -0
- package/lib/types/workouts/prompt/types.d.ts +9 -0
- package/lib/types/workouts/types.d.ts +1 -0
- package/package.json +5 -5
|
@@ -17,5 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
17
17
|
__exportStar(require("./strava"), exports);
|
|
18
18
|
__exportStar(require("./intervals"), exports);
|
|
19
19
|
__exportStar(require("./komoot"), exports);
|
|
20
|
+
__exportStar(require("./trainingpeaks"), exports);
|
|
20
21
|
__exportStar(require("./types"), exports);
|
|
21
22
|
__exportStar(require("./factory"), exports);
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
|
3
|
+
var useValue = arguments.length > 2;
|
|
4
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
5
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
6
|
+
}
|
|
7
|
+
return useValue ? value : void 0;
|
|
8
|
+
};
|
|
9
|
+
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
10
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
11
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
12
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
13
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
14
|
+
var _, done = false;
|
|
15
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
16
|
+
var context = {};
|
|
17
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
18
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
19
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
20
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
21
|
+
if (kind === "accessor") {
|
|
22
|
+
if (result === void 0) continue;
|
|
23
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
24
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
25
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
26
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
27
|
+
}
|
|
28
|
+
else if (_ = accept(result)) {
|
|
29
|
+
if (kind === "field") initializers.unshift(_);
|
|
30
|
+
else descriptor[key] = _;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
34
|
+
done = true;
|
|
35
|
+
};
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
exports.TrainingPeaksUpload = void 0;
|
|
38
|
+
const api_1 = require("../../api");
|
|
39
|
+
const TrainingPeaksAppConnection_1 = require("../../apps/trainingpeaks/TrainingPeaksAppConnection");
|
|
40
|
+
const Injection_1 = require("../../base/decorators/Injection");
|
|
41
|
+
const service_1 = require("../../base/service");
|
|
42
|
+
const types_1 = require("../../base/types");
|
|
43
|
+
const trainingpeaks_1 = require("../../apps/base/api/trainingpeaks");
|
|
44
|
+
const utils_1 = require("../../apps/base/api/trainingpeaks/utils");
|
|
45
|
+
const factory_1 = require("./factory");
|
|
46
|
+
const SUPPORTED_FORMATS = new Set(['tcx', 'fit']);
|
|
47
|
+
const EXISTING_ACTIVITY = 'existing';
|
|
48
|
+
let TrainingPeaksUpload = (() => {
|
|
49
|
+
let _classDecorators = [types_1.Singleton];
|
|
50
|
+
let _classDescriptor;
|
|
51
|
+
let _classExtraInitializers = [];
|
|
52
|
+
let _classThis;
|
|
53
|
+
let _classSuper = service_1.IncyclistService;
|
|
54
|
+
let _instanceExtraInitializers = [];
|
|
55
|
+
let _getTrainingPeaksAppConnection_decorators;
|
|
56
|
+
let _getFileSystem_decorators;
|
|
57
|
+
var TrainingPeaksUpload = class extends _classSuper {
|
|
58
|
+
static { _classThis = this; }
|
|
59
|
+
static {
|
|
60
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
61
|
+
_getTrainingPeaksAppConnection_decorators = [Injection_1.Injectable];
|
|
62
|
+
_getFileSystem_decorators = [Injection_1.Injectable];
|
|
63
|
+
__esDecorate(this, null, _getTrainingPeaksAppConnection_decorators, { kind: "method", name: "getTrainingPeaksAppConnection", static: false, private: false, access: { has: obj => "getTrainingPeaksAppConnection" in obj, get: obj => obj.getTrainingPeaksAppConnection }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
64
|
+
__esDecorate(this, null, _getFileSystem_decorators, { kind: "method", name: "getFileSystem", static: false, private: false, access: { has: obj => "getFileSystem" in obj, get: obj => obj.getFileSystem }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
65
|
+
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
|
|
66
|
+
TrainingPeaksUpload = _classThis = _classDescriptor.value;
|
|
67
|
+
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
68
|
+
__runInitializers(_classThis, _classExtraInitializers);
|
|
69
|
+
}
|
|
70
|
+
isInitialized = __runInitializers(this, _instanceExtraInitializers);
|
|
71
|
+
connection = new TrainingPeaksAppConnection_1.TrainingPeaksAppConnection();
|
|
72
|
+
constructor() {
|
|
73
|
+
super('TrainingPeaksUpload');
|
|
74
|
+
this.isInitialized = false;
|
|
75
|
+
this.init();
|
|
76
|
+
}
|
|
77
|
+
init() {
|
|
78
|
+
if (this.isInitialized)
|
|
79
|
+
return true;
|
|
80
|
+
this.isInitialized = this.getTrainingPeaksAppConnection().init();
|
|
81
|
+
return this.isInitialized;
|
|
82
|
+
}
|
|
83
|
+
isConnected() {
|
|
84
|
+
return this.getTrainingPeaksAppConnection().isConnected();
|
|
85
|
+
}
|
|
86
|
+
async upload(activity, format = 'TCX') {
|
|
87
|
+
if (!this.ensureInitialized()) {
|
|
88
|
+
this.logEvent({ message: 'TrainingPeaks Upload skipped', reason: 'not initialized' });
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (!this.isConnected())
|
|
92
|
+
return false;
|
|
93
|
+
try {
|
|
94
|
+
const lcFormat = format.toLowerCase();
|
|
95
|
+
this.logEvent({ message: 'TrainingPeaks Upload', format: lcFormat.toUpperCase() });
|
|
96
|
+
const fileName = this.getActivityFile(activity, lcFormat);
|
|
97
|
+
const data = await this.readFileAsBase64(fileName, lcFormat);
|
|
98
|
+
const res = await this.getApi().upload({
|
|
99
|
+
fileName: this.getUploadFileName(fileName, lcFormat),
|
|
100
|
+
data,
|
|
101
|
+
title: activity.title,
|
|
102
|
+
type: 'bike'
|
|
103
|
+
});
|
|
104
|
+
this.logEvent({ message: 'TrainingPeaks Upload success', activityId: res.trainingPeaksId });
|
|
105
|
+
this.setLink(activity, { activity_id: res.trainingPeaksId, url: this.getUrl() });
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
if (err instanceof trainingpeaks_1.TrainingPeaksDuplicateError)
|
|
110
|
+
return await this.onDuplicate(activity);
|
|
111
|
+
this.logEvent({ message: 'TrainingPeaks Upload failure', error: err.message });
|
|
112
|
+
this.setLink(activity, { error: err.message });
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async onDuplicate(activity) {
|
|
117
|
+
const id = await this.findExistingWorkout(activity);
|
|
118
|
+
this.logEvent({ message: 'TrainingPeaks Upload duplicate', activityId: id, found: id !== undefined });
|
|
119
|
+
this.setLink(activity, id
|
|
120
|
+
? { activity_id: id, url: this.getUrl() }
|
|
121
|
+
: { activity_id: EXISTING_ACTIVITY, url: this.getUrl() });
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
async findExistingWorkout(activity) {
|
|
125
|
+
try {
|
|
126
|
+
const start = new Date(activity.startTime);
|
|
127
|
+
if (Number.isNaN(start.valueOf()))
|
|
128
|
+
return undefined;
|
|
129
|
+
const workout = await this.getApi().findWorkout(start);
|
|
130
|
+
return workout ? String(workout.Id) : undefined;
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
this.logEvent({ message: 'TrainingPeaks Upload duplicate: workout not found', error: err.message });
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
getUrl() {
|
|
138
|
+
return this.getApi().getCalendarUrl();
|
|
139
|
+
}
|
|
140
|
+
getActivityFile(activity, format) {
|
|
141
|
+
if (!SUPPORTED_FORMATS.has(format))
|
|
142
|
+
throw new Error(`format ${format.toUpperCase()} is not supported by TrainingPeaks`);
|
|
143
|
+
const fileName = activity[`${format}FileName`];
|
|
144
|
+
if (!fileName)
|
|
145
|
+
throw new Error(`no ${format.toUpperCase()} file available for this activity`);
|
|
146
|
+
return fileName;
|
|
147
|
+
}
|
|
148
|
+
async readFileAsBase64(fileName, format) {
|
|
149
|
+
const fs = this.getFileSystem();
|
|
150
|
+
if (!(await fs.existsFile(fileName)))
|
|
151
|
+
throw new Error('activity file not found');
|
|
152
|
+
const content = await fs.readFile(fileName, 'base64');
|
|
153
|
+
if (!content)
|
|
154
|
+
throw new Error('activity file is empty');
|
|
155
|
+
const base64 = this.toBase64(content, format);
|
|
156
|
+
const contentType = this.getContentType(content);
|
|
157
|
+
const isXml = format === 'fit' ? undefined : this.isXml(base64);
|
|
158
|
+
this.logEvent({ message: 'TrainingPeaks Upload file', contentType, bytes: Math.floor(base64.length * 3 / 4), isXml });
|
|
159
|
+
if (isXml === false)
|
|
160
|
+
throw new Error(`activity file does not contain xml (content type: ${contentType})`);
|
|
161
|
+
return base64;
|
|
162
|
+
}
|
|
163
|
+
getContentType(content) {
|
|
164
|
+
if (typeof content !== 'object' || content === null)
|
|
165
|
+
return typeof content;
|
|
166
|
+
return content.constructor?.name ?? 'object';
|
|
167
|
+
}
|
|
168
|
+
toBase64(content, format) {
|
|
169
|
+
if (typeof content === 'string') {
|
|
170
|
+
const compact = content.replaceAll(/\s/g, '');
|
|
171
|
+
if ((0, utils_1.isBase64)(compact))
|
|
172
|
+
return compact;
|
|
173
|
+
if (format === 'fit')
|
|
174
|
+
throw new Error('binary file could not be read');
|
|
175
|
+
return Buffer.from(content, 'utf-8').toString('base64');
|
|
176
|
+
}
|
|
177
|
+
return this.toBuffer(content).toString('base64');
|
|
178
|
+
}
|
|
179
|
+
toBuffer(content) {
|
|
180
|
+
if (ArrayBuffer.isView(content))
|
|
181
|
+
return Buffer.from(content.buffer, content.byteOffset, content.byteLength);
|
|
182
|
+
if (content instanceof ArrayBuffer)
|
|
183
|
+
return Buffer.from(content);
|
|
184
|
+
const serialized = content;
|
|
185
|
+
if (serialized?.type === 'Buffer' && Array.isArray(serialized.data))
|
|
186
|
+
return Buffer.from(serialized.data);
|
|
187
|
+
throw new Error('activity file has an unsupported content type');
|
|
188
|
+
}
|
|
189
|
+
isXml(base64) {
|
|
190
|
+
return Buffer.from(base64.substring(0, 88), 'base64').toString('utf-8').trimStart().startsWith('<');
|
|
191
|
+
}
|
|
192
|
+
getUploadFileName(fileName, format) {
|
|
193
|
+
const name = fileName.split(/[\\/]/).at(-1) ?? '';
|
|
194
|
+
const dot = name.lastIndexOf('.');
|
|
195
|
+
const base = (dot >= 0 ? name.substring(0, dot) : name).replaceAll(/[\\/?%*:|"<>.\s]/g, '_');
|
|
196
|
+
return `${base || 'activity'}.${format}`;
|
|
197
|
+
}
|
|
198
|
+
setLink(activity, link) {
|
|
199
|
+
activity.links = { ...activity.links, trainingpeaks: link };
|
|
200
|
+
}
|
|
201
|
+
ensureInitialized() {
|
|
202
|
+
if (!this.isInitialized)
|
|
203
|
+
this.init();
|
|
204
|
+
return this.isInitialized;
|
|
205
|
+
}
|
|
206
|
+
getTrainingPeaksAppConnection() {
|
|
207
|
+
return this.connection;
|
|
208
|
+
}
|
|
209
|
+
getFileSystem() {
|
|
210
|
+
return (0, api_1.getBindings)().fs;
|
|
211
|
+
}
|
|
212
|
+
getApi() {
|
|
213
|
+
return this.getTrainingPeaksAppConnection().getApi();
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
return TrainingPeaksUpload = _classThis;
|
|
217
|
+
})();
|
|
218
|
+
exports.TrainingPeaksUpload = TrainingPeaksUpload;
|
|
219
|
+
const factory = new factory_1.ActivityUploadFactory();
|
|
220
|
+
factory.add('trainingpeaks', new TrainingPeaksUpload());
|
package/lib/cjs/api/rest/api.js
CHANGED
|
@@ -43,7 +43,7 @@ class ApiClient {
|
|
|
43
43
|
if (this.requestInterceptorId !== undefined)
|
|
44
44
|
return;
|
|
45
45
|
this.requestInterceptorId = client.interceptors.request.use((req) => this.onRequest(req));
|
|
46
|
-
this.responseInterceptorId = client.interceptors.response.use((res) => this.onResponse(res));
|
|
46
|
+
this.responseInterceptorId = client.interceptors.response.use((res) => this.onResponse(res), (err) => this.onError(err));
|
|
47
47
|
}
|
|
48
48
|
disableLogging() {
|
|
49
49
|
const client = this.client();
|
|
@@ -95,5 +95,25 @@ class ApiClient {
|
|
|
95
95
|
}
|
|
96
96
|
return res;
|
|
97
97
|
}
|
|
98
|
+
onError(err) {
|
|
99
|
+
try {
|
|
100
|
+
const { config, response } = err ?? {};
|
|
101
|
+
const { headers = {}, url, method, params } = config ?? {};
|
|
102
|
+
const tid = headers['x-transaction-id'];
|
|
103
|
+
const idx = tid ? this.requests.findIndex(r => r.tid === tid) : -1;
|
|
104
|
+
if (idx !== -1) {
|
|
105
|
+
const tsStart = this.requests[idx].ts;
|
|
106
|
+
this.requests.splice(idx, 1);
|
|
107
|
+
this.logger.logEvent({
|
|
108
|
+
message: 'api call', method, url, tid, status: response?.status ?? 'no response',
|
|
109
|
+
duration: Date.now() - tsStart, params, error: err.message
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
this.logger.logEvent({ message: 'error', fn: 'onError', error: e.message, stack: e.stack });
|
|
115
|
+
}
|
|
116
|
+
return Promise.reject(err);
|
|
117
|
+
}
|
|
98
118
|
}
|
|
99
119
|
exports.ApiClient = ApiClient;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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
|
+
const sleep_1 = require("../../../../utils/sleep");
|
|
9
|
+
const utils_1 = require("./utils");
|
|
10
|
+
const types_1 = require("./types");
|
|
11
|
+
const API_BASE_URL = 'https://api.trainingpeaks.com';
|
|
12
|
+
const AUTH_SERVER_URL = 'https://auth.incyclist.com';
|
|
13
|
+
const APP_URL = 'https://app.trainingpeaks.com';
|
|
14
|
+
const SANDBOX_APP_URL = 'https://app.sandbox.trainingpeaks.com';
|
|
15
|
+
const UPLOAD_CLIENT = 'Incyclist';
|
|
16
|
+
const MAX_WORKOUT_RANGE_DAYS = 45;
|
|
17
|
+
const UPLOAD_POLL_INTERVAL = 2000;
|
|
18
|
+
const UPLOAD_TIMEOUT = 60000;
|
|
19
|
+
const MAX_ERROR_DETAIL = 500;
|
|
20
|
+
const OFFSET_STEP_MS = 15 * 60 * 1000;
|
|
21
|
+
const MAX_OFFSET_MS = 14 * 60 * 60 * 1000;
|
|
22
|
+
const MATCH_TOLERANCE_MS = 1000;
|
|
23
|
+
class TrainingPeaksApi extends base_1.AppApiBase {
|
|
24
|
+
config;
|
|
25
|
+
logger;
|
|
26
|
+
observer;
|
|
27
|
+
constructor() {
|
|
28
|
+
super();
|
|
29
|
+
this.logger = new gd_eventlog_1.EventLogger('TrainingPeaksApi');
|
|
30
|
+
this.observer = new observer_1.Observer();
|
|
31
|
+
}
|
|
32
|
+
init(config) {
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.observer = this.observer ?? new observer_1.Observer();
|
|
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);
|
|
44
|
+
}
|
|
45
|
+
getCalendarUrl() {
|
|
46
|
+
const isSandbox = this.getBaseUrl().toLowerCase().includes('sandbox');
|
|
47
|
+
return (isSandbox ? SANDBOX_APP_URL : APP_URL) + '/#calendar';
|
|
48
|
+
}
|
|
49
|
+
async getWorkouts(start, end) {
|
|
50
|
+
const days = (end.valueOf() - start.valueOf()) / 86400000;
|
|
51
|
+
if (days < 0 || days > MAX_WORKOUT_RANGE_DAYS)
|
|
52
|
+
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/${this.formatDay(start)}/${this.formatDay(end)}`);
|
|
54
|
+
return (response.data ?? []);
|
|
55
|
+
}
|
|
56
|
+
async findWorkout(start) {
|
|
57
|
+
const from = new Date(start);
|
|
58
|
+
from.setDate(from.getDate() - 1);
|
|
59
|
+
const to = new Date(start);
|
|
60
|
+
to.setDate(to.getDate() + 1);
|
|
61
|
+
const workouts = await this.getWorkouts(from, to);
|
|
62
|
+
const candidates = workouts
|
|
63
|
+
.filter(w => w.Completed === true && w.WorkoutType?.toLowerCase() === 'bike')
|
|
64
|
+
.map(workout => ({ workout, deviation: this.getStartDeviation(workout, start) }))
|
|
65
|
+
.filter(c => c.deviation <= MATCH_TOLERANCE_MS)
|
|
66
|
+
.sort((a, b) => a.deviation - b.deviation);
|
|
67
|
+
return candidates[0]?.workout;
|
|
68
|
+
}
|
|
69
|
+
getStartDeviation(workout, start) {
|
|
70
|
+
if (!workout.StartTime)
|
|
71
|
+
return Number.POSITIVE_INFINITY;
|
|
72
|
+
const hasZone = /(Z|[+-]\d{2}:?\d{2})$/i.test(workout.StartTime);
|
|
73
|
+
const diff = new Date(hasZone ? workout.StartTime : workout.StartTime + 'Z').valueOf() - start.valueOf();
|
|
74
|
+
if (Number.isNaN(diff) || Math.abs(diff) > MAX_OFFSET_MS + MATCH_TOLERANCE_MS)
|
|
75
|
+
return Number.POSITIVE_INFINITY;
|
|
76
|
+
const rest = ((diff % OFFSET_STEP_MS) + OFFSET_STEP_MS) % OFFSET_STEP_MS;
|
|
77
|
+
return Math.min(rest, OFFSET_STEP_MS - rest);
|
|
78
|
+
}
|
|
79
|
+
async getWorkoutFile(workoutId, format = 'zwo') {
|
|
80
|
+
const response = await this.get(`/v2/workouts/wod/file/${workoutId}/?format=${format}`, { responseType: 'text' });
|
|
81
|
+
return response.data;
|
|
82
|
+
}
|
|
83
|
+
async upload(props) {
|
|
84
|
+
if (!(0, utils_1.isBase64)(props.data))
|
|
85
|
+
throw new Error('Upload failed, reason: data is not base64 encoded');
|
|
86
|
+
const data = this.prepareData(props);
|
|
87
|
+
this.logger.logEvent({
|
|
88
|
+
message: 'TrainingPeaks upload', format: props.fileName.split('.').at(-1)?.toLowerCase(),
|
|
89
|
+
bytes: this.getBase64Size(props.data), bytesSent: this.getBase64Size(data)
|
|
90
|
+
});
|
|
91
|
+
const request = {
|
|
92
|
+
UploadClient: UPLOAD_CLIENT,
|
|
93
|
+
Filename: props.fileName,
|
|
94
|
+
Data: data,
|
|
95
|
+
Title: props.title,
|
|
96
|
+
Comment: props.comment,
|
|
97
|
+
Type: props.type
|
|
98
|
+
};
|
|
99
|
+
const trackingId = await this.createUpload(request);
|
|
100
|
+
const trainingPeaksId = await this.waitForUploadResult(trackingId);
|
|
101
|
+
return { trainingPeaksId };
|
|
102
|
+
}
|
|
103
|
+
prepareData(props) {
|
|
104
|
+
if (!props.fileName.toLowerCase().endsWith('.tcx'))
|
|
105
|
+
return props.data;
|
|
106
|
+
const xml = Buffer.from(props.data, 'base64').toString('utf-8');
|
|
107
|
+
return Buffer.from((0, utils_1.trimXmlTextNodes)(xml), 'utf-8').toString('base64');
|
|
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);
|
|
125
|
+
}
|
|
126
|
+
async createUpload(request) {
|
|
127
|
+
let response;
|
|
128
|
+
try {
|
|
129
|
+
response = await this.request('post', '/v3/file', request);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
throw this.mapUploadError(err);
|
|
133
|
+
}
|
|
134
|
+
const location = response.headers?.location ?? response.headers?.Location;
|
|
135
|
+
const trackingId = location?.split('?')[0].split('/').findLast(part => part.length > 0);
|
|
136
|
+
if (!trackingId)
|
|
137
|
+
throw new Error('Upload failed, reason: no status url received');
|
|
138
|
+
return trackingId;
|
|
139
|
+
}
|
|
140
|
+
async waitForUploadResult(trackingId, attempt = 0) {
|
|
141
|
+
if (attempt >= Math.ceil(UPLOAD_TIMEOUT / UPLOAD_POLL_INTERVAL))
|
|
142
|
+
throw new Error('Upload failed, reason: timeout');
|
|
143
|
+
const response = await this.get(`/v3/status/${trackingId}`);
|
|
144
|
+
const status = response.data;
|
|
145
|
+
if (status?.Completed) {
|
|
146
|
+
const id = status.WorkoutIds?.[0];
|
|
147
|
+
if (id === undefined)
|
|
148
|
+
throw new Error('Upload failed, reason: ' + (status.Status ?? 'unknown'));
|
|
149
|
+
return String(id);
|
|
150
|
+
}
|
|
151
|
+
await this.waitForReady();
|
|
152
|
+
return await this.waitForUploadResult(trackingId, attempt + 1);
|
|
153
|
+
}
|
|
154
|
+
async waitForReady() {
|
|
155
|
+
await (0, sleep_1.sleep)(UPLOAD_POLL_INTERVAL);
|
|
156
|
+
}
|
|
157
|
+
mapUploadError(err) {
|
|
158
|
+
const status = err.response?.status;
|
|
159
|
+
if (status === 422)
|
|
160
|
+
return new types_1.TrainingPeaksDuplicateError();
|
|
161
|
+
if (status === 415)
|
|
162
|
+
return new Error('File format is not supported by TrainingPeaks');
|
|
163
|
+
if (status) {
|
|
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
|
+
}
|
|
226
|
+
}
|
|
227
|
+
getExpiration(data) {
|
|
228
|
+
const expiresIn = Number(data.expires_in);
|
|
229
|
+
if (Number.isFinite(expiresIn))
|
|
230
|
+
return new Date(Date.now() + expiresIn * 1000);
|
|
231
|
+
return new Date(Number(data.expiration));
|
|
232
|
+
}
|
|
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
|
+
}
|
|
255
|
+
exports.TrainingPeaksApi = TrainingPeaksApi;
|
|
@@ -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);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TrainingPeaksDuplicateError = void 0;
|
|
4
|
+
class TrainingPeaksDuplicateError extends Error {
|
|
5
|
+
constructor(message = 'Activity already exists in TrainingPeaks') {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'TrainingPeaksDuplicateError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
exports.TrainingPeaksDuplicateError = TrainingPeaksDuplicateError;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isBase64 = exports.trimXmlTextNodes = void 0;
|
|
4
|
+
const trimXmlTextNodes = (xml) => {
|
|
5
|
+
const parts = [];
|
|
6
|
+
let pos = 0;
|
|
7
|
+
while (pos < xml.length) {
|
|
8
|
+
const tagEnd = xml.indexOf('>', pos);
|
|
9
|
+
const nextTag = tagEnd === -1 ? -1 : xml.indexOf('<', tagEnd + 1);
|
|
10
|
+
if (nextTag === -1)
|
|
11
|
+
break;
|
|
12
|
+
parts.push(xml.substring(pos, tagEnd + 1), xml.substring(tagEnd + 1, nextTag).trim());
|
|
13
|
+
pos = nextTag;
|
|
14
|
+
}
|
|
15
|
+
parts.push(xml.substring(pos));
|
|
16
|
+
return parts.join('');
|
|
17
|
+
};
|
|
18
|
+
exports.trimXmlTextNodes = trimXmlTextNodes;
|
|
19
|
+
const isBase64 = (value) => /^[A-Za-z0-9+/]+={0,2}$/.test(value);
|
|
20
|
+
exports.isBase64 = isBase64;
|