incyclist-services 1.9.35 → 1.9.37

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.
Files changed (37) hide show
  1. package/lib/cjs/apps/base/api/oauth.js +7 -1
  2. package/lib/cjs/apps/base/api/trainingpeaks/api.js +56 -0
  3. package/lib/cjs/apps/base/app/OAuthAppConnection.js +1 -2
  4. package/lib/cjs/apps/trainingpeaks/TrainingPeaksAppConnection.js +4 -2
  5. package/lib/cjs/devices/ride/service.js +23 -9
  6. package/lib/cjs/ride/display/service.js +62 -3
  7. package/lib/cjs/routes/base/parsers/utils.js +9 -5
  8. package/lib/cjs/routes/list/cards/RouteCard.js +9 -15
  9. package/lib/cjs/utils/fileurl.js +11 -0
  10. package/lib/cjs/workouts/calendar/dedupe.js +53 -0
  11. package/lib/cjs/workouts/calendar/service.js +12 -6
  12. package/lib/cjs/workouts/calendar/sync/factory.js +5 -3
  13. package/lib/esm/apps/base/api/oauth.js +7 -1
  14. package/lib/esm/apps/base/api/trainingpeaks/api.js +56 -0
  15. package/lib/esm/apps/base/app/OAuthAppConnection.js +1 -2
  16. package/lib/esm/apps/trainingpeaks/TrainingPeaksAppConnection.js +4 -2
  17. package/lib/esm/devices/ride/service.js +23 -9
  18. package/lib/esm/ride/display/service.js +62 -3
  19. package/lib/esm/routes/base/parsers/utils.js +8 -4
  20. package/lib/esm/routes/list/cards/RouteCard.js +10 -16
  21. package/lib/esm/utils/fileurl.js +7 -0
  22. package/lib/esm/workouts/calendar/dedupe.js +48 -0
  23. package/lib/esm/workouts/calendar/service.js +12 -6
  24. package/lib/esm/workouts/calendar/sync/factory.js +5 -3
  25. package/lib/types/apps/base/api/oauth.d.ts +3 -1
  26. package/lib/types/apps/base/api/trainingpeaks/api.d.ts +10 -0
  27. package/lib/types/apps/base/api/trainingpeaks/types.d.ts +6 -2
  28. package/lib/types/apps/trainingpeaks/types.d.ts +3 -1
  29. package/lib/types/devices/ride/service.d.ts +6 -3
  30. package/lib/types/devices/ride/types.d.ts +4 -0
  31. package/lib/types/ride/base/types.d.ts +1 -1
  32. package/lib/types/ride/display/service.d.ts +7 -1
  33. package/lib/types/routes/base/parsers/utils.d.ts +3 -1
  34. package/lib/types/utils/fileurl.d.ts +1 -0
  35. package/lib/types/workouts/calendar/dedupe.d.ts +4 -0
  36. package/lib/types/workouts/calendar/service.d.ts +1 -0
  37. package/package.json +2 -2
@@ -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);
@@ -1064,7 +1073,7 @@ let DeviceRideService = (() => {
1064
1073
  return;
1065
1074
  return this.startAdapters(adapters, 'start', props);
1066
1075
  }
1067
- async retryStartDevice(udid, props) {
1076
+ async retryStartDevice(udid, props, options) {
1068
1077
  await this.lazyInit();
1069
1078
  const ai = this.getRideAdapters()?.find(a => a.udid === udid);
1070
1079
  if (!ai) {
@@ -1075,7 +1084,7 @@ let DeviceRideService = (() => {
1075
1084
  const retryAttempt = (this.retryCounts.get(udid) ?? 0) + 1;
1076
1085
  this.retryCounts.set(udid, retryAttempt);
1077
1086
  const token = this.beginStartAttempt(udid);
1078
- const promise = this.runDeviceRetry(ai, props, token);
1087
+ const promise = this.runDeviceRetry(ai, props, token, options);
1079
1088
  this.retryPromises.set(udid, promise);
1080
1089
  let retryResult;
1081
1090
  try {
@@ -1091,18 +1100,23 @@ let DeviceRideService = (() => {
1091
1100
  deviceRole: ai.isControl ? 'trainer' : 'sensor',
1092
1101
  retryResult,
1093
1102
  retryDurationMs: Date.now() - tsStart,
1094
- retryAttempt
1103
+ retryAttempt,
1104
+ retryTrigger: options?.trigger ?? 'user'
1095
1105
  });
1096
1106
  return retryResult === 'started';
1097
1107
  }
1098
- async runDeviceRetry(ai, props, token) {
1108
+ isDeviceReconnecting(udid) {
1109
+ const ai = this.rideAdapters?.find(a => a.udid === udid);
1110
+ return ai?.isRestarting === true || ai?.adapter?.isReconnecting?.() === true;
1111
+ }
1112
+ async runDeviceRetry(ai, props, token, options) {
1099
1113
  const udid = ai.udid;
1100
1114
  try {
1101
1115
  if (ai.adapter.isStarted()) {
1102
1116
  this.emit('start-success', this.getAdapterStateInfo(ai));
1103
1117
  return 'started';
1104
1118
  }
1105
- if (this.inFlightStarts.has(udid)) {
1119
+ if (this.inFlightStarts.has(udid) || options?.stopFirst) {
1106
1120
  const stopped = await this.stopWithTimeout(ai, DEVICE_RETRY_STOP_TIMEOUT_MS);
1107
1121
  if (this.startAttempts.get(udid) !== token)
1108
1122
  return 'cancelled';
@@ -140,6 +140,8 @@ let RideDisplayService = (() => {
140
140
  deviceAttempts = new Map();
141
141
  ignoredDevices = new Map();
142
142
  deviceRetries = 0;
143
+ autoRetried = new Set();
144
+ reconnecting = new Set();
143
145
  startTrigger = 'auto';
144
146
  fullRetryPending = false;
145
147
  constructor() {
@@ -283,6 +285,7 @@ let RideDisplayService = (() => {
283
285
  return;
284
286
  this.logDeviceButton('Retry device', device);
285
287
  this.ignoredDevices.delete(udid);
288
+ this.reconnecting.delete(udid);
286
289
  this.deviceRetries++;
287
290
  device.status = 'Starting';
288
291
  delete device.stateText;
@@ -321,7 +324,9 @@ let RideDisplayService = (() => {
321
324
  startPhase: props.startPhase ?? this.derivePhase(),
322
325
  startElapsedMs: this.getStartElapsed(),
323
326
  slowShown: this.slowShown,
324
- deviceRetries: this.deviceRetries
327
+ deviceRetries: this.deviceRetries,
328
+ deviceAutoRetries: this.autoRetried.size,
329
+ controlStartState: this.getControlStartState()
325
330
  });
326
331
  await this.cancelDeviceRetries();
327
332
  await this.stopRide({ noStateUpdates: true });
@@ -1206,6 +1211,7 @@ let RideDisplayService = (() => {
1206
1211
  this.observer?.emit('state-update', this.state);
1207
1212
  }
1208
1213
  async onDeviceStartOK(device) {
1214
+ this.reconnecting.delete(device.udid);
1209
1215
  this.onIgnoredDeviceStarted(device.udid);
1210
1216
  if (this.state !== 'Starting')
1211
1217
  return;
@@ -1265,12 +1271,15 @@ let RideDisplayService = (() => {
1265
1271
  this.logError(err, 'enableScreensaver');
1266
1272
  }
1267
1273
  }
1268
- onDeviceStartError(device) {
1274
+ onDeviceStartError(device, err) {
1269
1275
  if (this.state !== 'Starting')
1270
1276
  return;
1271
1277
  const startDevice = this.deviceInfo.find(d => d.udid === device.udid);
1272
1278
  if (!startDevice)
1273
1279
  return;
1280
+ if (this.tryAutoRetry(startDevice, err))
1281
+ return;
1282
+ this.reconnecting.delete(startDevice.udid);
1274
1283
  if (startDevice.status !== 'Error') {
1275
1284
  const key = startDevice.isControl ? 'Device' : 'Sensor';
1276
1285
  this.logEvent({ message: `${key} start error shown`, overlay: 'start overlay', device: startDevice.name, });
@@ -1279,6 +1288,50 @@ let RideDisplayService = (() => {
1279
1288
  startDevice.status = 'Error';
1280
1289
  this.checkStartStatus();
1281
1290
  }
1291
+ tryAutoRetry(startDevice, err) {
1292
+ if (!startDevice.isControl || startDevice.udid.startsWith('Simulator:') || this.isCancellingStart)
1293
+ return false;
1294
+ const skipReason = this.getAutoRetrySkipReason(startDevice);
1295
+ if (skipReason) {
1296
+ this.logEvent({ message: 'start auto-retry skipped', device: startDevice.name, reason: skipReason });
1297
+ return false;
1298
+ }
1299
+ this.startAutoRetry(startDevice, err);
1300
+ return true;
1301
+ }
1302
+ getAutoRetrySkipReason(startDevice) {
1303
+ if (this.autoRetried.has(startDevice.udid))
1304
+ return 'already retried';
1305
+ if (this.getDevicePairing()?.getActivity?.()?.pairing)
1306
+ return 'pairing attempt active';
1307
+ if (this.getDeviceRide().isDeviceReconnecting?.(startDevice.udid))
1308
+ return 'already reconnecting';
1309
+ return undefined;
1310
+ }
1311
+ startAutoRetry(startDevice, err) {
1312
+ const udid = startDevice.udid;
1313
+ this.logEvent({
1314
+ message: 'start auto-retry',
1315
+ device: startDevice.name,
1316
+ deviceRole: 'trainer',
1317
+ controlInterface: this.getBikeInterface(),
1318
+ reason: err?.message,
1319
+ startElapsedMs: this.getStartElapsed()
1320
+ });
1321
+ this.autoRetried.add(udid);
1322
+ this.reconnecting.add(udid);
1323
+ this.deviceRetries++;
1324
+ startDevice.status = 'Starting';
1325
+ delete startDevice.stateText;
1326
+ this.beginDeviceAttempt(udid);
1327
+ this.checkStartStatus();
1328
+ this.getDeviceRide().retryStartDevice(udid, this.getDeviceStartProps(), { stopFirst: true, trigger: 'auto' })
1329
+ .catch(retryErr => { this.logError(retryErr, 'startAutoRetry'); });
1330
+ }
1331
+ getControlStartState() {
1332
+ const control = this.deviceInfo?.find(d => d.isControl);
1333
+ return control ? this.getDeviceStartFields(control).startState : 'none';
1334
+ }
1282
1335
  onDeviceStartStatusUpdate(device, completed, total) {
1283
1336
  if (this.state !== 'Starting')
1284
1337
  return;
@@ -1382,6 +1435,7 @@ let RideDisplayService = (() => {
1382
1435
  const ignored = !d.isControl && this.ignoredDevices.has(d.udid);
1383
1436
  const starting = d.status === 'Starting';
1384
1437
  const slow = starting && !ignored && this.deviceAttempts.get(d.udid)?.slow === true;
1438
+ const reconnecting = starting && !d.stateText && this.reconnecting.has(d.udid);
1385
1439
  let startState = 'starting';
1386
1440
  if (d.status === 'Started')
1387
1441
  startState = 'started';
@@ -1389,10 +1443,12 @@ let RideDisplayService = (() => {
1389
1443
  startState = 'ignored';
1390
1444
  else if (d.stateText)
1391
1445
  startState = 'uploading';
1446
+ else if (reconnecting)
1447
+ startState = 'reconnecting';
1392
1448
  else if (d.status === 'Error')
1393
1449
  startState = d.isControl ? 'failed' : 'not-connected';
1394
1450
  if (d.isControl) {
1395
- return { startState, slow, canRetry: starting && slow && !d.stateText, canIgnore: false };
1451
+ return { startState, slow, canRetry: starting && slow && !d.stateText && !reconnecting, canIgnore: false };
1396
1452
  }
1397
1453
  const stuck = d.status === 'Error' || (starting && slow);
1398
1454
  return {
@@ -1450,12 +1506,15 @@ let RideDisplayService = (() => {
1450
1506
  this.deviceAttempts.clear();
1451
1507
  this.ignoredDevices.clear();
1452
1508
  this.deviceRetries = 0;
1509
+ this.autoRetried.clear();
1510
+ this.reconnecting.clear();
1453
1511
  this.startTrigger = 'auto';
1454
1512
  this.fullRetryPending = false;
1455
1513
  this.armStartTimer('devices-slow', this.getSlowThreshold(), () => { this.slowFlags.devices = true; });
1456
1514
  }
1457
1515
  restartDeviceTracking() {
1458
1516
  this.fullRetryPending = true;
1517
+ this.reconnecting.clear();
1459
1518
  this.slowFlags.devices = false;
1460
1519
  this.armStartTimer('devices-slow', this.getSlowThreshold(), () => { this.slowFlags.devices = true; });
1461
1520
  }
@@ -1,4 +1,5 @@
1
1
  import { getBindings } from "../../../api";
2
+ import { normalizeFileUrl } from '../../../utils/fileurl';
2
3
  export class BinaryReader {
3
4
  pos;
4
5
  buffer;
@@ -120,6 +121,7 @@ export const buildVideoUrl = (filePath) => {
120
121
  }
121
122
  return `video://${filePath}`;
122
123
  };
124
+ export { normalizeFileUrl };
123
125
  export const safeDecode = (path) => {
124
126
  try {
125
127
  return decodeURIComponent(path);
@@ -146,14 +148,16 @@ export const buildFileUrl = (normalizedPath) => {
146
148
  }
147
149
  return `file://${encodeURI(normalizedPath)}`;
148
150
  };
149
- export const fileUrlToPath = (url) => {
151
+ export const fileUrlToPath = (url, decode = true) => {
152
+ url = normalizeFileUrl(url);
150
153
  const scheme = ['file:///', 'video:///'].find(prefix => url?.startsWith(prefix));
151
154
  if (!scheme)
152
155
  return undefined;
153
156
  let path = url.slice(scheme.length - 1);
154
157
  while (path.startsWith('//'))
155
158
  path = path.slice(1);
156
- path = safeDecode(path);
159
+ if (decode)
160
+ path = safeDecode(path);
157
161
  return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
158
162
  };
159
163
  const buildUrlFromFile = (info, referenced) => {
@@ -178,7 +182,7 @@ const buildAbsolutePathTarget = (fileName, info, scheme) => {
178
182
  if (inputUrl.startsWith('incyclist:') || inputUrl.startsWith('file:')) {
179
183
  const parts = inputUrl.split('://');
180
184
  const targetPath = parts[1].replace(info.base, fileName);
181
- return `${scheme}://${targetPath}`;
185
+ return normalizeFileUrl(`${scheme}://${targetPath}`);
182
186
  }
183
187
  };
184
188
  const buildRelativePathTarget = (fileName, info, scheme) => {
@@ -187,7 +191,7 @@ const buildRelativePathTarget = (fileName, info, scheme) => {
187
191
  fileName = path.join(info.dir, fileName);
188
192
  target.file = fileName;
189
193
  if (isAbsolutePath(fileName)) {
190
- target.url = `${scheme}://${fileName}`;
194
+ target.url = normalizeFileUrl(`${scheme}://${fileName}`);
191
195
  }
192
196
  else {
193
197
  target.url = fileName;
@@ -36,7 +36,7 @@ import { getBindings } from "../../../api";
36
36
  import { Observer, PromiseObserver } from "../../../base/types/observer";
37
37
  import { useUserSettings } from "../../../settings";
38
38
  import { sleep } from "../../../utils/sleep";
39
- import { fileUrlToPath } from "../../base/parsers/utils";
39
+ import { fileUrlToPath, normalizeFileUrl } from "../../base/parsers/utils";
40
40
  import { BaseCard } from "./base";
41
41
  import { getRouteList, useRouteList } from "../service";
42
42
  import { RoutesDbLoader } from "../loaders/db";
@@ -169,7 +169,7 @@ let RouteCard = (() => {
169
169
  }
170
170
  async recoverDownloadState() {
171
171
  const descr = this.getRouteDescription();
172
- const localUrl = this.getRouteData()?.video?.url;
172
+ const localUrl = normalizeFileUrl(this.getRouteData()?.video?.url);
173
173
  if (!descr?.hasVideo || descr.isLocal || descr.isDownloaded)
174
174
  return false;
175
175
  if (!localUrl || !(localUrl.startsWith('video:///') || localUrl.startsWith('file:///')))
@@ -194,19 +194,12 @@ let RouteCard = (() => {
194
194
  async urlExists(videoUrl) {
195
195
  if (!videoUrl)
196
196
  return true;
197
- const normalizedUrl = videoUrl.replace('video:////', 'video:///').replace('file:////', 'file:///');
198
- let path = undefined;
199
- if (normalizedUrl.startsWith('file:///'))
200
- path = normalizedUrl.replace('file://', '');
201
- if (normalizedUrl.startsWith('video:///'))
202
- path = normalizedUrl.replace('video://', '');
203
- if (path && /^\/[A-Za-z]:[\\/]/.test(path))
204
- path = path.slice(1);
205
- if (path) {
206
- const decoded = this.cleanupEncoding(path);
197
+ const decoded = fileUrlToPath(videoUrl);
198
+ if (decoded) {
207
199
  if (await this.fileExists(decoded))
208
200
  return true;
209
- return decoded !== path ? await this.fileExists(path) : false;
201
+ const raw = fileUrlToPath(videoUrl, false);
202
+ return raw !== decoded ? await this.fileExists(raw) : false;
210
203
  }
211
204
  return true;
212
205
  }
@@ -729,17 +722,18 @@ let RouteCard = (() => {
729
722
  if (ext !== 'mp4' && ext !== 'avi') {
730
723
  return 'Unsupported video format - Please select MP4 or AVI';
731
724
  }
732
- const path = dropped.url.replace('file:///', '');
725
+ const droppedUrl = normalizeFileUrl(dropped.url);
726
+ const path = droppedUrl.replace('file:///', '');
733
727
  const exists = await this.fileExists(path);
734
728
  if (!exists) {
735
729
  return 'Could not open file';
736
730
  }
737
731
  const descr = this.getRouteDescription();
738
732
  const details = this.getRouteData();
739
- descr.videoUrl = dropped.url;
733
+ descr.videoUrl = droppedUrl;
740
734
  descr.videoFormat = ext;
741
735
  details.video.file = undefined;
742
- details.video.url = dropped.url;
736
+ details.video.url = droppedUrl;
743
737
  details.video.format = ext;
744
738
  this.save().catch(err => { this.logError(err, 'onVideoSelected'); });
745
739
  return null;
@@ -0,0 +1,7 @@
1
+ import { getBindings } from "../api";
2
+ export const normalizeFileUrl = (url) => {
3
+ if (!isWindows())
4
+ return url;
5
+ return url?.replace(/^(file|video):\/\/+(?=[A-Za-z]:(?:[\\/%]|$))/, '$1:///');
6
+ };
7
+ const isWindows = () => getBindings().appInfo?.getOS?.()?.platform === 'win32';
@@ -0,0 +1,48 @@
1
+ export const SOURCE_PRIORITY = ['trainingpeaks', 'trainerday', 'intervals'];
2
+ const getDuration = (step) => {
3
+ const duration = step.duration ?? ((step.end ?? 0) - (step.start ?? 0));
4
+ return Math.round(duration);
5
+ };
6
+ const flattenStep = (step) => {
7
+ if (step.steps) {
8
+ const inner = step.steps.flatMap(flattenStep);
9
+ const repeat = step.repeat && step.repeat > 0 ? step.repeat : 1;
10
+ return Array.from({ length: repeat }).flatMap(() => inner);
11
+ }
12
+ const { min, max, type } = step.power ?? {};
13
+ return [[getDuration(step), min === undefined ? undefined : Math.round(min), max === undefined ? undefined : Math.round(max), type]];
14
+ };
15
+ export const getContentKey = (entry) => {
16
+ const steps = entry.workout?.steps;
17
+ if (!steps?.length)
18
+ return undefined;
19
+ const flat = flattenStep({ steps, repeat: 1 });
20
+ return flat.length > 0 ? JSON.stringify(flat) : undefined;
21
+ };
22
+ const getPriority = (entry) => {
23
+ const idx = SOURCE_PRIORITY.indexOf(entry.source ?? '');
24
+ return idx === -1 ? SOURCE_PRIORITY.length : idx;
25
+ };
26
+ const getDayKey = (entry) => {
27
+ const day = entry.day instanceof Date ? entry.day : new Date(entry.day);
28
+ return `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`;
29
+ };
30
+ export const dedupeCalendarEntries = (entries) => {
31
+ const winners = new Map();
32
+ for (const entry of entries) {
33
+ const content = getContentKey(entry);
34
+ if (content === undefined)
35
+ continue;
36
+ const key = `${getDayKey(entry)}|${content}`;
37
+ const current = winners.get(key);
38
+ if (!current || (current.source !== entry.source && getPriority(entry) < getPriority(current)))
39
+ winners.set(key, entry);
40
+ }
41
+ return entries.filter(entry => {
42
+ const content = getContentKey(entry);
43
+ if (content === undefined)
44
+ return true;
45
+ const winner = winners.get(`${getDayKey(entry)}|${content}`);
46
+ return winner === entry || winner?.source === entry.source;
47
+ });
48
+ };
@@ -40,6 +40,7 @@ import { Observer, Singleton } from "../../base/types";
40
40
  import { useOnlineStatusMonitoring } from "../../monitoring";
41
41
  import { useUserSettings } from "../../settings";
42
42
  import { addDays, getFirstDayOfCurrentWeek } from "../../utils";
43
+ import { dedupeCalendarEntries } from "./dedupe";
43
44
  import { WorkoutSyncFactory } from "./sync";
44
45
  const SYNC_INTERVAL = 5 * 60 * 1000;
45
46
  const DB_NAME = 'calendar';
@@ -123,7 +124,7 @@ let WorkoutCalendarService = (() => {
123
124
  const from = getFirstDayOfCurrentWeek();
124
125
  const to = addDays(today, 7);
125
126
  if (this.workouts) {
126
- const workouts = this.workouts.filter(w => w.day?.valueOf() >= from.valueOf() && w.day.valueOf() <= to.valueOf());
127
+ const workouts = this.getVisibleWorkouts().filter(w => w.day?.valueOf() >= from.valueOf() && w.day.valueOf() <= to.valueOf());
127
128
  workouts.sort((a, b) => a.day.valueOf() - b.day.valueOf());
128
129
  return workouts.map(w => this.getScheduledWorkout(w));
129
130
  }
@@ -139,7 +140,7 @@ let WorkoutCalendarService = (() => {
139
140
  return undefined;
140
141
  const now = new Date();
141
142
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
142
- const entry = this.workouts.find(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
143
+ const entry = this.getVisibleWorkouts().find(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
143
144
  return entry ? this.getScheduledWorkout(entry) : undefined;
144
145
  }
145
146
  catch (err) {
@@ -211,6 +212,9 @@ let WorkoutCalendarService = (() => {
211
212
  catch {
212
213
  }
213
214
  }
215
+ getVisibleWorkouts() {
216
+ return dedupeCalendarEntries(this.workouts ?? []);
217
+ }
214
218
  getScheduledWorkout(w) {
215
219
  return { type: 'scheduled', name: w.workout.name, id: `${w.source ?? ''}:${w.workoutId}`, ...w };
216
220
  }
@@ -254,6 +258,7 @@ let WorkoutCalendarService = (() => {
254
258
  const observer = this.getWorkoutSyncFactory().sync(service);
255
259
  if (!observer) {
256
260
  done();
261
+ return;
257
262
  }
258
263
  this.syncInfo.observer = observer;
259
264
  this.syncInfo.listChanged = false;
@@ -274,8 +279,9 @@ let WorkoutCalendarService = (() => {
274
279
  }
275
280
  done();
276
281
  };
277
- const onloaded = (workouts) => {
278
- this.workouts = workouts.map(w => ({ ...w, observer: new Observer() }));
282
+ const onloaded = (workouts, services) => {
283
+ const kept = services ? (this.workouts ?? []).filter(w => !services.includes(w.source)) : [];
284
+ this.workouts = [...kept, ...workouts.map(w => ({ ...w, observer: new Observer() }))];
279
285
  this.checkIfScheduledCurrentDay();
280
286
  this.syncInfo.listChanged = true;
281
287
  this.syncInfo.contentChanged = true;
@@ -290,8 +296,8 @@ let WorkoutCalendarService = (() => {
290
296
  return;
291
297
  const now = new Date();
292
298
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
293
- const workouts = this.workouts?.filter(w => w.day?.toLocaleDateString() === today.toLocaleDateString()) ?? [];
294
- if (workouts?.length > 0) {
299
+ const workouts = this.getVisibleWorkouts().filter(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
300
+ if (workouts.length > 0) {
295
301
  this.emit('scheduled', workouts[0]);
296
302
  }
297
303
  }
@@ -76,20 +76,22 @@ let WorkoutSyncFactory = (() => {
76
76
  waitNextTick().then(() => { observer.stop(); }).catch(() => { });
77
77
  return null;
78
78
  }
79
+ const workouts = [];
80
+ const loadedServices = [];
79
81
  target.forEach(sp => {
80
- const workouts = [];
81
82
  const { service, syncProvider } = sp;
82
83
  const so = syncProvider.sync();
83
84
  const onDone = (event, entries, service) => {
84
85
  if (event === 'loaded') {
86
+ loadedServices.push(service);
85
87
  entries.forEach(w => {
86
88
  workouts.push({ ...w, source: service });
87
89
  });
88
90
  }
89
91
  delete syncs[service];
90
92
  if (Object.keys(syncs).length === 0) {
91
- if (event === 'loaded') {
92
- observer.emit('loaded', workouts);
93
+ if (loadedServices.length > 0) {
94
+ observer.emit('loaded', workouts, loadedServices);
93
95
  }
94
96
  else {
95
97
  observer.emit('done');
@@ -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;