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
@@ -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);
@@ -1070,7 +1079,7 @@ let DeviceRideService = (() => {
1070
1079
  return;
1071
1080
  return this.startAdapters(adapters, 'start', props);
1072
1081
  }
1073
- async retryStartDevice(udid, props) {
1082
+ async retryStartDevice(udid, props, options) {
1074
1083
  await this.lazyInit();
1075
1084
  const ai = this.getRideAdapters()?.find(a => a.udid === udid);
1076
1085
  if (!ai) {
@@ -1081,7 +1090,7 @@ let DeviceRideService = (() => {
1081
1090
  const retryAttempt = (this.retryCounts.get(udid) ?? 0) + 1;
1082
1091
  this.retryCounts.set(udid, retryAttempt);
1083
1092
  const token = this.beginStartAttempt(udid);
1084
- const promise = this.runDeviceRetry(ai, props, token);
1093
+ const promise = this.runDeviceRetry(ai, props, token, options);
1085
1094
  this.retryPromises.set(udid, promise);
1086
1095
  let retryResult;
1087
1096
  try {
@@ -1097,18 +1106,23 @@ let DeviceRideService = (() => {
1097
1106
  deviceRole: ai.isControl ? 'trainer' : 'sensor',
1098
1107
  retryResult,
1099
1108
  retryDurationMs: Date.now() - tsStart,
1100
- retryAttempt
1109
+ retryAttempt,
1110
+ retryTrigger: options?.trigger ?? 'user'
1101
1111
  });
1102
1112
  return retryResult === 'started';
1103
1113
  }
1104
- async runDeviceRetry(ai, props, token) {
1114
+ isDeviceReconnecting(udid) {
1115
+ const ai = this.rideAdapters?.find(a => a.udid === udid);
1116
+ return ai?.isRestarting === true || ai?.adapter?.isReconnecting?.() === true;
1117
+ }
1118
+ async runDeviceRetry(ai, props, token, options) {
1105
1119
  const udid = ai.udid;
1106
1120
  try {
1107
1121
  if (ai.adapter.isStarted()) {
1108
1122
  this.emit('start-success', this.getAdapterStateInfo(ai));
1109
1123
  return 'started';
1110
1124
  }
1111
- if (this.inFlightStarts.has(udid)) {
1125
+ if (this.inFlightStarts.has(udid) || options?.stopFirst) {
1112
1126
  const stopped = await this.stopWithTimeout(ai, timeouts_1.DEVICE_RETRY_STOP_TIMEOUT_MS);
1113
1127
  if (this.startAttempts.get(udid) !== token)
1114
1128
  return 'cancelled';
@@ -143,6 +143,8 @@ let RideDisplayService = (() => {
143
143
  deviceAttempts = new Map();
144
144
  ignoredDevices = new Map();
145
145
  deviceRetries = 0;
146
+ autoRetried = new Set();
147
+ reconnecting = new Set();
146
148
  startTrigger = 'auto';
147
149
  fullRetryPending = false;
148
150
  constructor() {
@@ -286,6 +288,7 @@ let RideDisplayService = (() => {
286
288
  return;
287
289
  this.logDeviceButton('Retry device', device);
288
290
  this.ignoredDevices.delete(udid);
291
+ this.reconnecting.delete(udid);
289
292
  this.deviceRetries++;
290
293
  device.status = 'Starting';
291
294
  delete device.stateText;
@@ -324,7 +327,9 @@ let RideDisplayService = (() => {
324
327
  startPhase: props.startPhase ?? this.derivePhase(),
325
328
  startElapsedMs: this.getStartElapsed(),
326
329
  slowShown: this.slowShown,
327
- deviceRetries: this.deviceRetries
330
+ deviceRetries: this.deviceRetries,
331
+ deviceAutoRetries: this.autoRetried.size,
332
+ controlStartState: this.getControlStartState()
328
333
  });
329
334
  await this.cancelDeviceRetries();
330
335
  await this.stopRide({ noStateUpdates: true });
@@ -1209,6 +1214,7 @@ let RideDisplayService = (() => {
1209
1214
  this.observer?.emit('state-update', this.state);
1210
1215
  }
1211
1216
  async onDeviceStartOK(device) {
1217
+ this.reconnecting.delete(device.udid);
1212
1218
  this.onIgnoredDeviceStarted(device.udid);
1213
1219
  if (this.state !== 'Starting')
1214
1220
  return;
@@ -1268,12 +1274,15 @@ let RideDisplayService = (() => {
1268
1274
  this.logError(err, 'enableScreensaver');
1269
1275
  }
1270
1276
  }
1271
- onDeviceStartError(device) {
1277
+ onDeviceStartError(device, err) {
1272
1278
  if (this.state !== 'Starting')
1273
1279
  return;
1274
1280
  const startDevice = this.deviceInfo.find(d => d.udid === device.udid);
1275
1281
  if (!startDevice)
1276
1282
  return;
1283
+ if (this.tryAutoRetry(startDevice, err))
1284
+ return;
1285
+ this.reconnecting.delete(startDevice.udid);
1277
1286
  if (startDevice.status !== 'Error') {
1278
1287
  const key = startDevice.isControl ? 'Device' : 'Sensor';
1279
1288
  this.logEvent({ message: `${key} start error shown`, overlay: 'start overlay', device: startDevice.name, });
@@ -1282,6 +1291,50 @@ let RideDisplayService = (() => {
1282
1291
  startDevice.status = 'Error';
1283
1292
  this.checkStartStatus();
1284
1293
  }
1294
+ tryAutoRetry(startDevice, err) {
1295
+ if (!startDevice.isControl || startDevice.udid.startsWith('Simulator:') || this.isCancellingStart)
1296
+ return false;
1297
+ const skipReason = this.getAutoRetrySkipReason(startDevice);
1298
+ if (skipReason) {
1299
+ this.logEvent({ message: 'start auto-retry skipped', device: startDevice.name, reason: skipReason });
1300
+ return false;
1301
+ }
1302
+ this.startAutoRetry(startDevice, err);
1303
+ return true;
1304
+ }
1305
+ getAutoRetrySkipReason(startDevice) {
1306
+ if (this.autoRetried.has(startDevice.udid))
1307
+ return 'already retried';
1308
+ if (this.getDevicePairing()?.getActivity?.()?.pairing)
1309
+ return 'pairing attempt active';
1310
+ if (this.getDeviceRide().isDeviceReconnecting?.(startDevice.udid))
1311
+ return 'already reconnecting';
1312
+ return undefined;
1313
+ }
1314
+ startAutoRetry(startDevice, err) {
1315
+ const udid = startDevice.udid;
1316
+ this.logEvent({
1317
+ message: 'start auto-retry',
1318
+ device: startDevice.name,
1319
+ deviceRole: 'trainer',
1320
+ controlInterface: this.getBikeInterface(),
1321
+ reason: err?.message,
1322
+ startElapsedMs: this.getStartElapsed()
1323
+ });
1324
+ this.autoRetried.add(udid);
1325
+ this.reconnecting.add(udid);
1326
+ this.deviceRetries++;
1327
+ startDevice.status = 'Starting';
1328
+ delete startDevice.stateText;
1329
+ this.beginDeviceAttempt(udid);
1330
+ this.checkStartStatus();
1331
+ this.getDeviceRide().retryStartDevice(udid, this.getDeviceStartProps(), { stopFirst: true, trigger: 'auto' })
1332
+ .catch(retryErr => { this.logError(retryErr, 'startAutoRetry'); });
1333
+ }
1334
+ getControlStartState() {
1335
+ const control = this.deviceInfo?.find(d => d.isControl);
1336
+ return control ? this.getDeviceStartFields(control).startState : 'none';
1337
+ }
1285
1338
  onDeviceStartStatusUpdate(device, completed, total) {
1286
1339
  if (this.state !== 'Starting')
1287
1340
  return;
@@ -1385,6 +1438,7 @@ let RideDisplayService = (() => {
1385
1438
  const ignored = !d.isControl && this.ignoredDevices.has(d.udid);
1386
1439
  const starting = d.status === 'Starting';
1387
1440
  const slow = starting && !ignored && this.deviceAttempts.get(d.udid)?.slow === true;
1441
+ const reconnecting = starting && !d.stateText && this.reconnecting.has(d.udid);
1388
1442
  let startState = 'starting';
1389
1443
  if (d.status === 'Started')
1390
1444
  startState = 'started';
@@ -1392,10 +1446,12 @@ let RideDisplayService = (() => {
1392
1446
  startState = 'ignored';
1393
1447
  else if (d.stateText)
1394
1448
  startState = 'uploading';
1449
+ else if (reconnecting)
1450
+ startState = 'reconnecting';
1395
1451
  else if (d.status === 'Error')
1396
1452
  startState = d.isControl ? 'failed' : 'not-connected';
1397
1453
  if (d.isControl) {
1398
- return { startState, slow, canRetry: starting && slow && !d.stateText, canIgnore: false };
1454
+ return { startState, slow, canRetry: starting && slow && !d.stateText && !reconnecting, canIgnore: false };
1399
1455
  }
1400
1456
  const stuck = d.status === 'Error' || (starting && slow);
1401
1457
  return {
@@ -1453,12 +1509,15 @@ let RideDisplayService = (() => {
1453
1509
  this.deviceAttempts.clear();
1454
1510
  this.ignoredDevices.clear();
1455
1511
  this.deviceRetries = 0;
1512
+ this.autoRetried.clear();
1513
+ this.reconnecting.clear();
1456
1514
  this.startTrigger = 'auto';
1457
1515
  this.fullRetryPending = false;
1458
1516
  this.armStartTimer('devices-slow', this.getSlowThreshold(), () => { this.slowFlags.devices = true; });
1459
1517
  }
1460
1518
  restartDeviceTracking() {
1461
1519
  this.fullRetryPending = true;
1520
+ this.reconnecting.clear();
1462
1521
  this.slowFlags.devices = false;
1463
1522
  this.armStartTimer('devices-slow', this.getSlowThreshold(), () => { this.slowFlags.devices = true; });
1464
1523
  }
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getUtf8Data = exports.fixIncorrectFileInfo = exports.parseInformations = exports.fileUrlToPath = exports.buildFileUrl = exports.safeEncode = exports.safeDecode = exports.buildVideoUrl = exports.getReferencedFileInfo = exports.BinaryReader = void 0;
3
+ exports.getUtf8Data = exports.fixIncorrectFileInfo = exports.parseInformations = exports.fileUrlToPath = exports.buildFileUrl = exports.safeEncode = exports.safeDecode = exports.normalizeFileUrl = exports.buildVideoUrl = exports.getReferencedFileInfo = exports.BinaryReader = void 0;
4
4
  const api_1 = require("../../../api");
5
+ const fileurl_1 = require("../../../utils/fileurl");
6
+ Object.defineProperty(exports, "normalizeFileUrl", { enumerable: true, get: function () { return fileurl_1.normalizeFileUrl; } });
5
7
  class BinaryReader {
6
8
  pos;
7
9
  buffer;
@@ -155,14 +157,16 @@ const buildFileUrl = (normalizedPath) => {
155
157
  return `file://${encodeURI(normalizedPath)}`;
156
158
  };
157
159
  exports.buildFileUrl = buildFileUrl;
158
- const fileUrlToPath = (url) => {
160
+ const fileUrlToPath = (url, decode = true) => {
161
+ url = (0, fileurl_1.normalizeFileUrl)(url);
159
162
  const scheme = ['file:///', 'video:///'].find(prefix => url?.startsWith(prefix));
160
163
  if (!scheme)
161
164
  return undefined;
162
165
  let path = url.slice(scheme.length - 1);
163
166
  while (path.startsWith('//'))
164
167
  path = path.slice(1);
165
- path = (0, exports.safeDecode)(path);
168
+ if (decode)
169
+ path = (0, exports.safeDecode)(path);
166
170
  return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
167
171
  };
168
172
  exports.fileUrlToPath = fileUrlToPath;
@@ -188,7 +192,7 @@ const buildAbsolutePathTarget = (fileName, info, scheme) => {
188
192
  if (inputUrl.startsWith('incyclist:') || inputUrl.startsWith('file:')) {
189
193
  const parts = inputUrl.split('://');
190
194
  const targetPath = parts[1].replace(info.base, fileName);
191
- return `${scheme}://${targetPath}`;
195
+ return (0, fileurl_1.normalizeFileUrl)(`${scheme}://${targetPath}`);
192
196
  }
193
197
  };
194
198
  const buildRelativePathTarget = (fileName, info, scheme) => {
@@ -197,7 +201,7 @@ const buildRelativePathTarget = (fileName, info, scheme) => {
197
201
  fileName = path.join(info.dir, fileName);
198
202
  target.file = fileName;
199
203
  if (isAbsolutePath(fileName)) {
200
- target.url = `${scheme}://${fileName}`;
204
+ target.url = (0, fileurl_1.normalizeFileUrl)(`${scheme}://${fileName}`);
201
205
  }
202
206
  else {
203
207
  target.url = fileName;
@@ -172,7 +172,7 @@ let RouteCard = (() => {
172
172
  }
173
173
  async recoverDownloadState() {
174
174
  const descr = this.getRouteDescription();
175
- const localUrl = this.getRouteData()?.video?.url;
175
+ const localUrl = (0, utils_1.normalizeFileUrl)(this.getRouteData()?.video?.url);
176
176
  if (!descr?.hasVideo || descr.isLocal || descr.isDownloaded)
177
177
  return false;
178
178
  if (!localUrl || !(localUrl.startsWith('video:///') || localUrl.startsWith('file:///')))
@@ -197,19 +197,12 @@ let RouteCard = (() => {
197
197
  async urlExists(videoUrl) {
198
198
  if (!videoUrl)
199
199
  return true;
200
- const normalizedUrl = videoUrl.replace('video:////', 'video:///').replace('file:////', 'file:///');
201
- let path = undefined;
202
- if (normalizedUrl.startsWith('file:///'))
203
- path = normalizedUrl.replace('file://', '');
204
- if (normalizedUrl.startsWith('video:///'))
205
- path = normalizedUrl.replace('video://', '');
206
- if (path && /^\/[A-Za-z]:[\\/]/.test(path))
207
- path = path.slice(1);
208
- if (path) {
209
- const decoded = this.cleanupEncoding(path);
200
+ const decoded = (0, utils_1.fileUrlToPath)(videoUrl);
201
+ if (decoded) {
210
202
  if (await this.fileExists(decoded))
211
203
  return true;
212
- return decoded !== path ? await this.fileExists(path) : false;
204
+ const raw = (0, utils_1.fileUrlToPath)(videoUrl, false);
205
+ return raw !== decoded ? await this.fileExists(raw) : false;
213
206
  }
214
207
  return true;
215
208
  }
@@ -732,17 +725,18 @@ let RouteCard = (() => {
732
725
  if (ext !== 'mp4' && ext !== 'avi') {
733
726
  return 'Unsupported video format - Please select MP4 or AVI';
734
727
  }
735
- const path = dropped.url.replace('file:///', '');
728
+ const droppedUrl = (0, utils_1.normalizeFileUrl)(dropped.url);
729
+ const path = droppedUrl.replace('file:///', '');
736
730
  const exists = await this.fileExists(path);
737
731
  if (!exists) {
738
732
  return 'Could not open file';
739
733
  }
740
734
  const descr = this.getRouteDescription();
741
735
  const details = this.getRouteData();
742
- descr.videoUrl = dropped.url;
736
+ descr.videoUrl = droppedUrl;
743
737
  descr.videoFormat = ext;
744
738
  details.video.file = undefined;
745
- details.video.url = dropped.url;
739
+ details.video.url = droppedUrl;
746
740
  details.video.format = ext;
747
741
  this.save().catch(err => { this.logError(err, 'onVideoSelected'); });
748
742
  return null;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeFileUrl = void 0;
4
+ const api_1 = require("../api");
5
+ const normalizeFileUrl = (url) => {
6
+ if (!isWindows())
7
+ return url;
8
+ return url?.replace(/^(file|video):\/\/+(?=[A-Za-z]:(?:[\\/%]|$))/, '$1:///');
9
+ };
10
+ exports.normalizeFileUrl = normalizeFileUrl;
11
+ const isWindows = () => (0, api_1.getBindings)().appInfo?.getOS?.()?.platform === 'win32';
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dedupeCalendarEntries = exports.getContentKey = exports.SOURCE_PRIORITY = void 0;
4
+ exports.SOURCE_PRIORITY = ['trainingpeaks', 'trainerday', 'intervals'];
5
+ const getDuration = (step) => {
6
+ const duration = step.duration ?? ((step.end ?? 0) - (step.start ?? 0));
7
+ return Math.round(duration);
8
+ };
9
+ const flattenStep = (step) => {
10
+ if (step.steps) {
11
+ const inner = step.steps.flatMap(flattenStep);
12
+ const repeat = step.repeat && step.repeat > 0 ? step.repeat : 1;
13
+ return Array.from({ length: repeat }).flatMap(() => inner);
14
+ }
15
+ const { min, max, type } = step.power ?? {};
16
+ return [[getDuration(step), min === undefined ? undefined : Math.round(min), max === undefined ? undefined : Math.round(max), type]];
17
+ };
18
+ const getContentKey = (entry) => {
19
+ const steps = entry.workout?.steps;
20
+ if (!steps?.length)
21
+ return undefined;
22
+ const flat = flattenStep({ steps, repeat: 1 });
23
+ return flat.length > 0 ? JSON.stringify(flat) : undefined;
24
+ };
25
+ exports.getContentKey = getContentKey;
26
+ const getPriority = (entry) => {
27
+ const idx = exports.SOURCE_PRIORITY.indexOf(entry.source ?? '');
28
+ return idx === -1 ? exports.SOURCE_PRIORITY.length : idx;
29
+ };
30
+ const getDayKey = (entry) => {
31
+ const day = entry.day instanceof Date ? entry.day : new Date(entry.day);
32
+ return `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`;
33
+ };
34
+ const dedupeCalendarEntries = (entries) => {
35
+ const winners = new Map();
36
+ for (const entry of entries) {
37
+ const content = (0, exports.getContentKey)(entry);
38
+ if (content === undefined)
39
+ continue;
40
+ const key = `${getDayKey(entry)}|${content}`;
41
+ const current = winners.get(key);
42
+ if (!current || (current.source !== entry.source && getPriority(entry) < getPriority(current)))
43
+ winners.set(key, entry);
44
+ }
45
+ return entries.filter(entry => {
46
+ const content = (0, exports.getContentKey)(entry);
47
+ if (content === undefined)
48
+ return true;
49
+ const winner = winners.get(`${getDayKey(entry)}|${content}`);
50
+ return winner === entry || winner?.source === entry.source;
51
+ });
52
+ };
53
+ exports.dedupeCalendarEntries = dedupeCalendarEntries;
@@ -43,6 +43,7 @@ const types_1 = require("../../base/types");
43
43
  const monitoring_1 = require("../../monitoring");
44
44
  const settings_1 = require("../../settings");
45
45
  const utils_1 = require("../../utils");
46
+ const dedupe_1 = require("./dedupe");
46
47
  const sync_1 = require("./sync");
47
48
  const SYNC_INTERVAL = 5 * 60 * 1000;
48
49
  const DB_NAME = 'calendar';
@@ -126,7 +127,7 @@ let WorkoutCalendarService = (() => {
126
127
  const from = (0, utils_1.getFirstDayOfCurrentWeek)();
127
128
  const to = (0, utils_1.addDays)(today, 7);
128
129
  if (this.workouts) {
129
- const workouts = this.workouts.filter(w => w.day?.valueOf() >= from.valueOf() && w.day.valueOf() <= to.valueOf());
130
+ const workouts = this.getVisibleWorkouts().filter(w => w.day?.valueOf() >= from.valueOf() && w.day.valueOf() <= to.valueOf());
130
131
  workouts.sort((a, b) => a.day.valueOf() - b.day.valueOf());
131
132
  return workouts.map(w => this.getScheduledWorkout(w));
132
133
  }
@@ -142,7 +143,7 @@ let WorkoutCalendarService = (() => {
142
143
  return undefined;
143
144
  const now = new Date();
144
145
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
145
- const entry = this.workouts.find(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
146
+ const entry = this.getVisibleWorkouts().find(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
146
147
  return entry ? this.getScheduledWorkout(entry) : undefined;
147
148
  }
148
149
  catch (err) {
@@ -214,6 +215,9 @@ let WorkoutCalendarService = (() => {
214
215
  catch {
215
216
  }
216
217
  }
218
+ getVisibleWorkouts() {
219
+ return (0, dedupe_1.dedupeCalendarEntries)(this.workouts ?? []);
220
+ }
217
221
  getScheduledWorkout(w) {
218
222
  return { type: 'scheduled', name: w.workout.name, id: `${w.source ?? ''}:${w.workoutId}`, ...w };
219
223
  }
@@ -257,6 +261,7 @@ let WorkoutCalendarService = (() => {
257
261
  const observer = this.getWorkoutSyncFactory().sync(service);
258
262
  if (!observer) {
259
263
  done();
264
+ return;
260
265
  }
261
266
  this.syncInfo.observer = observer;
262
267
  this.syncInfo.listChanged = false;
@@ -277,8 +282,9 @@ let WorkoutCalendarService = (() => {
277
282
  }
278
283
  done();
279
284
  };
280
- const onloaded = (workouts) => {
281
- this.workouts = workouts.map(w => ({ ...w, observer: new types_1.Observer() }));
285
+ const onloaded = (workouts, services) => {
286
+ const kept = services ? (this.workouts ?? []).filter(w => !services.includes(w.source)) : [];
287
+ this.workouts = [...kept, ...workouts.map(w => ({ ...w, observer: new types_1.Observer() }))];
282
288
  this.checkIfScheduledCurrentDay();
283
289
  this.syncInfo.listChanged = true;
284
290
  this.syncInfo.contentChanged = true;
@@ -293,8 +299,8 @@ let WorkoutCalendarService = (() => {
293
299
  return;
294
300
  const now = new Date();
295
301
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
296
- const workouts = this.workouts?.filter(w => w.day?.toLocaleDateString() === today.toLocaleDateString()) ?? [];
297
- if (workouts?.length > 0) {
302
+ const workouts = this.getVisibleWorkouts().filter(w => w.day?.toLocaleDateString() === today.toLocaleDateString());
303
+ if (workouts.length > 0) {
298
304
  this.emit('scheduled', workouts[0]);
299
305
  }
300
306
  }
@@ -79,20 +79,22 @@ let WorkoutSyncFactory = (() => {
79
79
  (0, utils_1.waitNextTick)().then(() => { observer.stop(); }).catch(() => { });
80
80
  return null;
81
81
  }
82
+ const workouts = [];
83
+ const loadedServices = [];
82
84
  target.forEach(sp => {
83
- const workouts = [];
84
85
  const { service, syncProvider } = sp;
85
86
  const so = syncProvider.sync();
86
87
  const onDone = (event, entries, service) => {
87
88
  if (event === 'loaded') {
89
+ loadedServices.push(service);
88
90
  entries.forEach(w => {
89
91
  workouts.push({ ...w, source: service });
90
92
  });
91
93
  }
92
94
  delete syncs[service];
93
95
  if (Object.keys(syncs).length === 0) {
94
- if (event === 'loaded') {
95
- observer.emit('loaded', workouts);
96
+ if (loadedServices.length > 0) {
97
+ observer.emit('loaded', workouts, loadedServices);
96
98
  }
97
99
  else {
98
100
  observer.emit('done');