incyclist-services 1.9.35 → 1.9.36

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.
@@ -46,7 +46,7 @@ class OAuthAppApiBase extends base_1.AppApiBase {
46
46
  ...config
47
47
  };
48
48
  try {
49
- return await this.getApi().request(request);
49
+ return await this.send(request);
50
50
  }
51
51
  catch (err) {
52
52
  if (options.checkRevoked !== false)
@@ -54,6 +54,9 @@ class OAuthAppApiBase extends base_1.AppApiBase {
54
54
  throw err;
55
55
  }
56
56
  }
57
+ async send(request) {
58
+ return await this.getApi().request(request);
59
+ }
57
60
  async checkRevoked(err) {
58
61
  const { refreshPath, authCheckPath, name } = this.props;
59
62
  if (refreshPath || !authCheckPath || this.authFailed || err?.response?.status !== 401)
@@ -135,6 +138,7 @@ class OAuthAppApiBase extends base_1.AppApiBase {
135
138
  this.config.accessToken = data.access_token;
136
139
  this.config.refreshToken = data.refresh_token;
137
140
  this.config.expiration = this.getExpiration(data);
141
+ this.applyRefreshResponse(data);
138
142
  this.logger.logEvent({ message: `${name} refresh token result`, status: 'success' });
139
143
  this.observer.emit('token.updated', this.config);
140
144
  }
@@ -144,6 +148,8 @@ class OAuthAppApiBase extends base_1.AppApiBase {
144
148
  throw err;
145
149
  }
146
150
  }
151
+ applyRefreshResponse(_data) {
152
+ }
147
153
  getSetting(key, defValue) {
148
154
  try {
149
155
  const settings = this.getUserSettings();
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TrainingPeaksApi = void 0;
4
+ const api_1 = require("../../../../api");
4
5
  const sleep_1 = require("../../../../utils/sleep");
5
6
  const xml_1 = require("../../../../utils/xml");
6
7
  const utils_1 = require("../../utils");
@@ -10,6 +11,8 @@ const types_1 = require("./types");
10
11
  const APP_URL = 'https://app.trainingpeaks.com';
11
12
  const SANDBOX_APP_URL = 'https://app.sandbox.trainingpeaks.com';
12
13
  const UPLOAD_CLIENT = 'Incyclist';
14
+ const DEFAULT_USER_AGENT = 'Incyclist/1.0.0';
15
+ const VALID_USER_AGENT = /^[A-Za-z0-9._-]{1,32}\/[A-Za-z0-9._+-]{1,32}$/;
13
16
  const MAX_WORKOUT_RANGE_DAYS = 45;
14
17
  const UPLOAD_POLL_INTERVAL = 2000;
15
18
  const UPLOAD_TIMEOUT = 60000;
@@ -129,6 +132,59 @@ class TrainingPeaksApi extends oauth_1.OAuthAppApiBase {
129
132
  return new Error('File format is not supported by TrainingPeaks');
130
133
  return this.mapUploadRejection(err);
131
134
  }
135
+ getAuthHeaders() {
136
+ return { ...super.getAuthHeaders(), 'User-Agent': this.getUserAgent() };
137
+ }
138
+ getUserAgent() {
139
+ const received = this.config?.userAgent;
140
+ return this.isValidUserAgent(received) ? received : DEFAULT_USER_AGENT;
141
+ }
142
+ isValidUserAgent(value) {
143
+ return typeof value === 'string' && VALID_USER_AGENT.test(value);
144
+ }
145
+ applyRefreshResponse(data) {
146
+ if (this.isValidUserAgent(data.user_agent))
147
+ this.config.userAgent = data.user_agent;
148
+ }
149
+ getBindings() {
150
+ return (0, api_1.getBindings)();
151
+ }
152
+ async send(request) {
153
+ const binding = this.getBindings()?.fetch;
154
+ if (!binding)
155
+ return await super.send(request);
156
+ return await this.sendViaFetchBinding(binding, request);
157
+ }
158
+ async sendViaFetchBinding(binding, request) {
159
+ const headers = { Accept: 'application/json, text/plain, */*', ...request.headers };
160
+ let body;
161
+ if (request.data !== undefined) {
162
+ body = typeof request.data === 'string' ? request.data : JSON.stringify(request.data);
163
+ headers['Content-Type'] ??= 'application/json';
164
+ }
165
+ const res = await binding.fetch(request.url, { method: (request.method ?? 'get').toUpperCase(), headers, body });
166
+ const response = {
167
+ data: request.responseType === 'text' ? res.data : this.parseBody(res.data),
168
+ status: res.status,
169
+ statusText: res.statusText,
170
+ headers: res.headers,
171
+ config: request
172
+ };
173
+ if (!res.ok)
174
+ throw Object.assign(new Error(`Request failed with status code ${res.status}`), { response });
175
+ return response;
176
+ }
177
+ parseBody(text) {
178
+ const trimmed = text?.trim();
179
+ if (!trimmed?.startsWith('{') && !trimmed?.startsWith('['))
180
+ return text;
181
+ try {
182
+ return JSON.parse(trimmed);
183
+ }
184
+ catch {
185
+ return text;
186
+ }
187
+ }
132
188
  getExpiration(data) {
133
189
  const expiresIn = Number(data.expires_in);
134
190
  if (Number.isFinite(expiresIn))
@@ -85,8 +85,7 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
85
85
  }
86
86
  }
87
87
  updateConfig(config) {
88
- const { accessToken, refreshToken, expiration } = config;
89
- this.config = { ...this.config, accessToken, refreshToken, expiration };
88
+ this.config = { ...this.config, ...config };
90
89
  this.saveCredentials();
91
90
  }
92
91
  saveCredentials(config) {
@@ -74,7 +74,8 @@ let TrainingPeaksAppConnection = (() => {
74
74
  id: credentials?.id === undefined ? undefined : String(credentials.id),
75
75
  accessToken: credentials?.accesstoken,
76
76
  refreshToken: credentials?.refreshtoken,
77
- expiration: (0, utils_1.parseExpiration)(credentials?.expiration)
77
+ expiration: (0, utils_1.parseExpiration)(credentials?.expiration),
78
+ ...(credentials?.useragent ? { userAgent: credentials.useragent } : {})
78
79
  };
79
80
  }
80
81
  createCredentials(config) {
@@ -82,7 +83,8 @@ let TrainingPeaksAppConnection = (() => {
82
83
  id: config.id,
83
84
  accesstoken: config.accessToken,
84
85
  refreshtoken: config.refreshToken,
85
- expiration: config.expiration?.toISOString()
86
+ expiration: config.expiration?.toISOString(),
87
+ ...(config.userAgent ? { useragent: config.userAgent } : {})
86
88
  };
87
89
  }
88
90
  };
@@ -826,7 +826,7 @@ let DeviceRideService = (() => {
826
826
  try {
827
827
  const ifName = unhealthy.adapter.getInterface();
828
828
  const adapters = (this.rideAdapters ?? [unhealthy]).filter(ai => ai.adapter.getInterface() === ifName);
829
- const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
829
+ const stillHealthy = adapters.filter(ai => this.isDeliveringData(ai));
830
830
  this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
831
831
  noDataSince: (tsNow - tsLastData),
832
832
  tsLastData: tsLastDataStr, stillHealthy: stillHealthy.length, onSameInterface: adapters.length });
@@ -844,11 +844,13 @@ let DeviceRideService = (() => {
844
844
  unhealthy.isRestarting = false;
845
845
  }
846
846
  }
847
+ isDeliveringData(ai) {
848
+ return !ai.isRestarting && (ai.isHealthy === undefined || ai.isHealthy === true);
849
+ }
847
850
  async reconnectInterface(ifName, adapters) {
848
851
  if (this.reconnectBusy) {
849
852
  return;
850
853
  }
851
- this.reconnectBusy = true;
852
854
  if (ifName === 'simulator')
853
855
  return;
854
856
  if (ifName === 'ble') {
@@ -858,9 +860,17 @@ let DeviceRideService = (() => {
858
860
  catch (err) {
859
861
  this.logError(err, 'reconnectInterface');
860
862
  }
861
- this.reconnectBusy = false;
862
863
  return;
863
864
  }
865
+ this.reconnectBusy = true;
866
+ try {
867
+ await this.restartInterfaceAndAdapters(ifName, adapters);
868
+ }
869
+ finally {
870
+ this.reconnectBusy = false;
871
+ }
872
+ }
873
+ async restartInterfaceAndAdapters(ifName, adapters) {
864
874
  const restarting = adapters.filter(ai => ai.isRestarting) ?? [];
865
875
  if (restarting.length) {
866
876
  this.logEvent({ message: 'interrupt restarts', interface: ifName });
@@ -883,7 +893,6 @@ let DeviceRideService = (() => {
883
893
  catch (err) {
884
894
  this.logEvent({ message: 'restart interface failed', interface: ifName, reason: err.message });
885
895
  }
886
- this.reconnectBusy = false;
887
896
  }
888
897
  async performInterfaceReconnect(ifName) {
889
898
  const i = incyclist_devices_1.InterfaceFactory.create(ifName);
@@ -43,7 +43,7 @@ export class OAuthAppApiBase extends AppApiBase {
43
43
  ...config
44
44
  };
45
45
  try {
46
- return await this.getApi().request(request);
46
+ return await this.send(request);
47
47
  }
48
48
  catch (err) {
49
49
  if (options.checkRevoked !== false)
@@ -51,6 +51,9 @@ export class OAuthAppApiBase extends AppApiBase {
51
51
  throw err;
52
52
  }
53
53
  }
54
+ async send(request) {
55
+ return await this.getApi().request(request);
56
+ }
54
57
  async checkRevoked(err) {
55
58
  const { refreshPath, authCheckPath, name } = this.props;
56
59
  if (refreshPath || !authCheckPath || this.authFailed || err?.response?.status !== 401)
@@ -132,6 +135,7 @@ export class OAuthAppApiBase extends AppApiBase {
132
135
  this.config.accessToken = data.access_token;
133
136
  this.config.refreshToken = data.refresh_token;
134
137
  this.config.expiration = this.getExpiration(data);
138
+ this.applyRefreshResponse(data);
135
139
  this.logger.logEvent({ message: `${name} refresh token result`, status: 'success' });
136
140
  this.observer.emit('token.updated', this.config);
137
141
  }
@@ -141,6 +145,8 @@ export class OAuthAppApiBase extends AppApiBase {
141
145
  throw err;
142
146
  }
143
147
  }
148
+ applyRefreshResponse(_data) {
149
+ }
144
150
  getSetting(key, defValue) {
145
151
  try {
146
152
  const settings = this.getUserSettings();
@@ -1,3 +1,4 @@
1
+ import { getBindings } from '../../../../api';
1
2
  import { sleep } from '../../../../utils/sleep';
2
3
  import { trimXmlTextNodes } from '../../../../utils/xml';
3
4
  import { formatDay } from '../../utils';
@@ -7,6 +8,8 @@ import { TrainingPeaksDuplicateError } from './types';
7
8
  const APP_URL = 'https://app.trainingpeaks.com';
8
9
  const SANDBOX_APP_URL = 'https://app.sandbox.trainingpeaks.com';
9
10
  const UPLOAD_CLIENT = 'Incyclist';
11
+ const DEFAULT_USER_AGENT = 'Incyclist/1.0.0';
12
+ const VALID_USER_AGENT = /^[A-Za-z0-9._-]{1,32}\/[A-Za-z0-9._+-]{1,32}$/;
10
13
  const MAX_WORKOUT_RANGE_DAYS = 45;
11
14
  const UPLOAD_POLL_INTERVAL = 2000;
12
15
  const UPLOAD_TIMEOUT = 60000;
@@ -126,6 +129,59 @@ export class TrainingPeaksApi extends OAuthAppApiBase {
126
129
  return new Error('File format is not supported by TrainingPeaks');
127
130
  return this.mapUploadRejection(err);
128
131
  }
132
+ getAuthHeaders() {
133
+ return { ...super.getAuthHeaders(), 'User-Agent': this.getUserAgent() };
134
+ }
135
+ getUserAgent() {
136
+ const received = this.config?.userAgent;
137
+ return this.isValidUserAgent(received) ? received : DEFAULT_USER_AGENT;
138
+ }
139
+ isValidUserAgent(value) {
140
+ return typeof value === 'string' && VALID_USER_AGENT.test(value);
141
+ }
142
+ applyRefreshResponse(data) {
143
+ if (this.isValidUserAgent(data.user_agent))
144
+ this.config.userAgent = data.user_agent;
145
+ }
146
+ getBindings() {
147
+ return getBindings();
148
+ }
149
+ async send(request) {
150
+ const binding = this.getBindings()?.fetch;
151
+ if (!binding)
152
+ return await super.send(request);
153
+ return await this.sendViaFetchBinding(binding, request);
154
+ }
155
+ async sendViaFetchBinding(binding, request) {
156
+ const headers = { Accept: 'application/json, text/plain, */*', ...request.headers };
157
+ let body;
158
+ if (request.data !== undefined) {
159
+ body = typeof request.data === 'string' ? request.data : JSON.stringify(request.data);
160
+ headers['Content-Type'] ??= 'application/json';
161
+ }
162
+ const res = await binding.fetch(request.url, { method: (request.method ?? 'get').toUpperCase(), headers, body });
163
+ const response = {
164
+ data: request.responseType === 'text' ? res.data : this.parseBody(res.data),
165
+ status: res.status,
166
+ statusText: res.statusText,
167
+ headers: res.headers,
168
+ config: request
169
+ };
170
+ if (!res.ok)
171
+ throw Object.assign(new Error(`Request failed with status code ${res.status}`), { response });
172
+ return response;
173
+ }
174
+ parseBody(text) {
175
+ const trimmed = text?.trim();
176
+ if (!trimmed?.startsWith('{') && !trimmed?.startsWith('['))
177
+ return text;
178
+ try {
179
+ return JSON.parse(trimmed);
180
+ }
181
+ catch {
182
+ return text;
183
+ }
184
+ }
129
185
  getExpiration(data) {
130
186
  const expiresIn = Number(data.expires_in);
131
187
  if (Number.isFinite(expiresIn))
@@ -82,8 +82,7 @@ export class OAuthAppConnection extends ConnectedAppService {
82
82
  }
83
83
  }
84
84
  updateConfig(config) {
85
- const { accessToken, refreshToken, expiration } = config;
86
- this.config = { ...this.config, accessToken, refreshToken, expiration };
85
+ this.config = { ...this.config, ...config };
87
86
  this.saveCredentials();
88
87
  }
89
88
  saveCredentials(config) {
@@ -71,7 +71,8 @@ let TrainingPeaksAppConnection = (() => {
71
71
  id: credentials?.id === undefined ? undefined : String(credentials.id),
72
72
  accessToken: credentials?.accesstoken,
73
73
  refreshToken: credentials?.refreshtoken,
74
- expiration: parseExpiration(credentials?.expiration)
74
+ expiration: parseExpiration(credentials?.expiration),
75
+ ...(credentials?.useragent ? { userAgent: credentials.useragent } : {})
75
76
  };
76
77
  }
77
78
  createCredentials(config) {
@@ -79,7 +80,8 @@ let TrainingPeaksAppConnection = (() => {
79
80
  id: config.id,
80
81
  accesstoken: config.accessToken,
81
82
  refreshtoken: config.refreshToken,
82
- expiration: config.expiration?.toISOString()
83
+ expiration: config.expiration?.toISOString(),
84
+ ...(config.userAgent ? { useragent: config.userAgent } : {})
83
85
  };
84
86
  }
85
87
  };
@@ -820,7 +820,7 @@ let DeviceRideService = (() => {
820
820
  try {
821
821
  const ifName = unhealthy.adapter.getInterface();
822
822
  const adapters = (this.rideAdapters ?? [unhealthy]).filter(ai => ai.adapter.getInterface() === ifName);
823
- const stillHealthy = adapters.filter(ai => ai.isHealthy === undefined || ai.isHealthy === true);
823
+ const stillHealthy = adapters.filter(ai => this.isDeliveringData(ai));
824
824
  this.logEvent({ message: 'reconnect confirmed', device: unhealthy.adapter.getUniqueName(), udid: unhealthy.udid,
825
825
  noDataSince: (tsNow - tsLastData),
826
826
  tsLastData: tsLastDataStr, stillHealthy: stillHealthy.length, onSameInterface: adapters.length });
@@ -838,11 +838,13 @@ let DeviceRideService = (() => {
838
838
  unhealthy.isRestarting = false;
839
839
  }
840
840
  }
841
+ isDeliveringData(ai) {
842
+ return !ai.isRestarting && (ai.isHealthy === undefined || ai.isHealthy === true);
843
+ }
841
844
  async reconnectInterface(ifName, adapters) {
842
845
  if (this.reconnectBusy) {
843
846
  return;
844
847
  }
845
- this.reconnectBusy = true;
846
848
  if (ifName === 'simulator')
847
849
  return;
848
850
  if (ifName === 'ble') {
@@ -852,9 +854,17 @@ let DeviceRideService = (() => {
852
854
  catch (err) {
853
855
  this.logError(err, 'reconnectInterface');
854
856
  }
855
- this.reconnectBusy = false;
856
857
  return;
857
858
  }
859
+ this.reconnectBusy = true;
860
+ try {
861
+ await this.restartInterfaceAndAdapters(ifName, adapters);
862
+ }
863
+ finally {
864
+ this.reconnectBusy = false;
865
+ }
866
+ }
867
+ async restartInterfaceAndAdapters(ifName, adapters) {
858
868
  const restarting = adapters.filter(ai => ai.isRestarting) ?? [];
859
869
  if (restarting.length) {
860
870
  this.logEvent({ message: 'interrupt restarts', interface: ifName });
@@ -877,7 +887,6 @@ let DeviceRideService = (() => {
877
887
  catch (err) {
878
888
  this.logEvent({ message: 'restart interface failed', interface: ifName, reason: err.message });
879
889
  }
880
- this.reconnectBusy = false;
881
890
  }
882
891
  async performInterfaceReconnect(ifName) {
883
892
  const i = InterfaceFactory.create(ifName);
@@ -1,4 +1,4 @@
1
- import { AxiosInstance, AxiosResponse } from 'axios';
1
+ import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
2
2
  import { EventLogger } from 'gd-eventlog';
3
3
  import { Observer } from '../../../base/types/observer';
4
4
  import { AppApiBase } from './base';
@@ -18,6 +18,7 @@ export declare abstract class OAuthAppApiBase<TConfig extends OAuthAppConfig = O
18
18
  protected request(method: 'get' | 'post' | 'put', url: string, data?: object, config?: object, options?: {
19
19
  checkRevoked?: boolean;
20
20
  }): Promise<AxiosResponse>;
21
+ protected send(request: AxiosRequestConfig): Promise<AxiosResponse>;
21
22
  protected checkRevoked(err: any): Promise<void>;
22
23
  protected isTokenRejected(path: string): Promise<boolean>;
23
24
  protected get(url: string, config?: object): Promise<AxiosResponse>;
@@ -28,6 +29,7 @@ export declare abstract class OAuthAppApiBase<TConfig extends OAuthAppConfig = O
28
29
  protected refreshTokenOnce(): Promise<void>;
29
30
  protected isTokenStillValid(): boolean;
30
31
  protected refreshToken(): Promise<void>;
32
+ protected applyRefreshResponse(_data: TRefresh): void;
31
33
  protected getSetting<T>(key: string, defValue: T | null): T | null;
32
34
  protected getAuthServerUrl(): string;
33
35
  protected getBaseUrl(): string;
@@ -1,3 +1,5 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import type { IFetchBinding } from '../../../../api/fetch/types';
1
3
  import { OAuthAppApiBase } from '../oauth';
2
4
  import { TrainingPeaksConfig, TrainingPeaksFileFormat, TrainingPeaksRefreshTokenResponse, TrainingPeaksUploadProps, TrainingPeaksUploadRequest, TrainingPeaksUploadResult, TrainingPeaksWorkout } from './types';
3
5
  export declare class TrainingPeaksApi extends OAuthAppApiBase<TrainingPeaksConfig, TrainingPeaksRefreshTokenResponse> {
@@ -13,5 +15,13 @@ export declare class TrainingPeaksApi extends OAuthAppApiBase<TrainingPeaksConfi
13
15
  protected waitForUploadResult(trackingId: string, attempt?: number): Promise<string>;
14
16
  protected waitForReady(): Promise<void>;
15
17
  protected mapUploadError(err: any): Error;
18
+ protected getAuthHeaders(): Record<string, string>;
19
+ protected getUserAgent(): string;
20
+ protected isValidUserAgent(value: unknown): value is string;
21
+ protected applyRefreshResponse(data: TrainingPeaksRefreshTokenResponse): void;
22
+ protected getBindings(): import("../../../../api").IncyclistBindings;
23
+ protected send(request: AxiosRequestConfig): Promise<AxiosResponse>;
24
+ protected sendViaFetchBinding(binding: IFetchBinding, request: AxiosRequestConfig): Promise<AxiosResponse>;
25
+ protected parseBody(text: string): unknown;
16
26
  protected getExpiration(data: TrainingPeaksRefreshTokenResponse): Date;
17
27
  }
@@ -1,6 +1,10 @@
1
1
  import type { OAuthAppConfig, OAuthRefreshTokenResponse } from '../types';
2
- export type TrainingPeaksConfig = OAuthAppConfig;
3
- export type TrainingPeaksRefreshTokenResponse = OAuthRefreshTokenResponse;
2
+ export type TrainingPeaksConfig = OAuthAppConfig & {
3
+ userAgent?: string;
4
+ };
5
+ export type TrainingPeaksRefreshTokenResponse = OAuthRefreshTokenResponse & {
6
+ user_agent?: string;
7
+ };
4
8
  export type TrainingPeaksFileFormat = 'zwo' | 'erg' | 'mrc' | 'fit' | 'json';
5
9
  export type TrainingPeaksWorkout = {
6
10
  Id: number;
@@ -1,2 +1,4 @@
1
1
  import { OAuthAppCredentials } from '../base/types';
2
- export type TrainingPeaksCredentials = OAuthAppCredentials;
2
+ export type TrainingPeaksCredentials = OAuthAppCredentials & {
3
+ useragent?: string;
4
+ };
@@ -95,7 +95,9 @@ export declare class DeviceRideService extends IncyclistService {
95
95
  private removeOnDatahandler;
96
96
  stopHealthCheck(ai: AdapterRideInfo): void;
97
97
  prepareReconnect(unhealthy: AdapterRideInfo): Promise<void>;
98
+ private isDeliveringData;
98
99
  private reconnectInterface;
100
+ private restartInterfaceAndAdapters;
99
101
  private performInterfaceReconnect;
100
102
  protected stopAllAdaptersOnInterface(ifName: string): Promise<void>;
101
103
  private stopAdapters;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "incyclist-services",
3
- "version": "1.9.35",
3
+ "version": "1.9.36",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },
7
7
  "dependencies": {
8
8
  "@garmin/fitsdk": "^21.222.0",
9
9
  "axios": "^1.21.1",
10
- "incyclist-devices": "^3.0.49",
10
+ "incyclist-devices": "^3.0.50",
11
11
  "promise.any": "^2.0.6",
12
12
  "semver": "^7.8.6",
13
13
  "tcx-builder": "^1.1.1",