incyclist-services 1.9.29 → 1.9.31

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 (165) hide show
  1. package/lib/cjs/activities/ride/service.js +72 -33
  2. package/lib/cjs/activities/upload/index.js +1 -0
  3. package/lib/cjs/activities/upload/trainerday.js +216 -0
  4. package/lib/cjs/activities/upload/trainingpeaks.js +2 -2
  5. package/lib/cjs/apps/base/api/index.js +1 -0
  6. package/lib/cjs/apps/base/api/oauth.js +130 -0
  7. package/lib/cjs/apps/base/api/trainerday/api.js +58 -0
  8. package/lib/cjs/apps/base/api/trainerday/index.js +18 -0
  9. package/lib/cjs/apps/base/api/trainerday/types.js +4 -0
  10. package/lib/cjs/apps/base/api/trainingpeaks/api.js +17 -133
  11. package/lib/cjs/apps/base/utils.js +34 -1
  12. package/lib/cjs/apps/index.js +1 -0
  13. package/lib/cjs/apps/service.js +2 -0
  14. package/lib/cjs/apps/trainerday/TrainerDayAppConnection.js +91 -0
  15. package/lib/cjs/apps/trainerday/index.js +18 -0
  16. package/lib/cjs/apps/trainerday/types.js +2 -0
  17. package/lib/cjs/base/dialogs/index.js +17 -0
  18. package/lib/cjs/base/dialogs/service.js +34 -0
  19. package/lib/cjs/base/dialogs/types.js +2 -0
  20. package/lib/cjs/settings/dialog/index.js +17 -0
  21. package/lib/cjs/settings/dialog/support/base/service.js +177 -0
  22. package/lib/cjs/settings/dialog/support/base/types.js +2 -0
  23. package/lib/cjs/settings/dialog/support/desktop/service.js +68 -0
  24. package/lib/cjs/settings/dialog/support/index.js +19 -0
  25. package/lib/cjs/settings/dialog/support/mobile/service.js +68 -0
  26. package/lib/cjs/settings/dialog/support/types.js +2 -0
  27. package/lib/cjs/settings/display/support/service.js +138 -21
  28. package/lib/cjs/settings/page/index.js +17 -0
  29. package/lib/cjs/settings/page/support/base/service.js +178 -0
  30. package/lib/cjs/settings/page/support/base/types.js +2 -0
  31. package/lib/cjs/settings/page/support/desktop/service.js +68 -0
  32. package/lib/cjs/settings/page/support/index.js +19 -0
  33. package/lib/cjs/settings/page/support/mobile/service.js +68 -0
  34. package/lib/cjs/settings/page/support/types.js +2 -0
  35. package/lib/cjs/settings/support/copy.js +48 -0
  36. package/lib/cjs/settings/support/donation.js +21 -0
  37. package/lib/cjs/settings/support/index.js +19 -0
  38. package/lib/cjs/settings/support/mailto.js +31 -0
  39. package/lib/cjs/settings/support/types.js +2 -0
  40. package/lib/cjs/settings/support/urls.js +27 -0
  41. package/lib/cjs/utils/base64.js +52 -0
  42. package/lib/cjs/utils/index.js +2 -0
  43. package/lib/cjs/utils/utf8.js +66 -0
  44. package/lib/cjs/utils/xml.js +16 -1
  45. package/lib/cjs/workouts/base/parsers/trainerday/converter.js +139 -0
  46. package/lib/cjs/workouts/base/parsers/trainerday/types.js +2 -0
  47. package/lib/cjs/workouts/calendar/sync/base/provider.js +150 -0
  48. package/lib/cjs/workouts/calendar/sync/base/types.js +2 -0
  49. package/lib/cjs/workouts/calendar/sync/index.js +1 -0
  50. package/lib/cjs/workouts/calendar/sync/trainerday/provider.js +142 -0
  51. package/lib/cjs/workouts/calendar/sync/trainingpeaks/provider.js +26 -101
  52. package/lib/esm/activities/ride/service.js +72 -33
  53. package/lib/esm/activities/upload/index.js +1 -0
  54. package/lib/esm/activities/upload/trainerday.js +213 -0
  55. package/lib/esm/activities/upload/trainingpeaks.js +1 -1
  56. package/lib/esm/apps/base/api/index.js +1 -0
  57. package/lib/esm/apps/base/api/oauth.js +126 -0
  58. package/lib/esm/apps/base/api/trainerday/api.js +54 -0
  59. package/lib/esm/apps/base/api/trainerday/index.js +2 -0
  60. package/lib/esm/apps/base/api/trainerday/types.js +1 -0
  61. package/lib/esm/apps/base/api/trainerday/utils.js +117 -0
  62. package/lib/esm/apps/base/api/trainingpeaks/api.js +15 -131
  63. package/lib/esm/apps/base/utils.js +29 -0
  64. package/lib/esm/apps/index.js +1 -0
  65. package/lib/esm/apps/service.js +2 -0
  66. package/lib/esm/apps/trainerday/TrainerDayAppConnection.js +88 -0
  67. package/lib/esm/apps/trainerday/index.js +2 -0
  68. package/lib/esm/apps/trainerday/types.js +1 -0
  69. package/lib/esm/base/dialogs/index.js +1 -0
  70. package/lib/esm/base/dialogs/service.js +30 -0
  71. package/lib/esm/base/dialogs/types.js +1 -0
  72. package/lib/esm/settings/dialog/index.js +1 -0
  73. package/lib/esm/settings/dialog/support/base/service.js +174 -0
  74. package/lib/esm/settings/dialog/support/base/types.js +1 -0
  75. package/lib/esm/settings/dialog/support/desktop/service.js +65 -0
  76. package/lib/esm/settings/dialog/support/index.js +12 -0
  77. package/lib/esm/settings/dialog/support/mobile/service.js +65 -0
  78. package/lib/esm/settings/dialog/support/types.js +1 -0
  79. package/lib/esm/settings/display/support/dialog-types.js +1 -0
  80. package/lib/esm/settings/display/support/service.js +138 -21
  81. package/lib/esm/settings/page/index.js +1 -0
  82. package/lib/esm/settings/page/support/base/service.js +175 -0
  83. package/lib/esm/settings/page/support/base/types.js +1 -0
  84. package/lib/esm/settings/page/support/desktop/service.js +65 -0
  85. package/lib/esm/settings/page/support/index.js +12 -0
  86. package/lib/esm/settings/page/support/mobile/service.js +65 -0
  87. package/lib/esm/settings/page/support/types.js +1 -0
  88. package/lib/esm/settings/support/copy.js +43 -0
  89. package/lib/esm/settings/support/donation.js +16 -0
  90. package/lib/esm/settings/support/index.js +3 -0
  91. package/lib/esm/settings/support/mailto.js +27 -0
  92. package/lib/esm/settings/support/types.js +1 -0
  93. package/lib/esm/settings/support/urls.js +16 -0
  94. package/lib/esm/utils/base64.js +45 -0
  95. package/lib/esm/utils/index.js +2 -0
  96. package/lib/esm/utils/utf8.js +59 -0
  97. package/lib/esm/utils/xml.js +14 -0
  98. package/lib/esm/workouts/base/parsers/trainerday/converter.js +133 -0
  99. package/lib/esm/workouts/base/parsers/trainerday/types.js +1 -0
  100. package/lib/esm/workouts/calendar/sync/base/provider.js +147 -0
  101. package/lib/esm/workouts/calendar/sync/base/types.js +1 -0
  102. package/lib/esm/workouts/calendar/sync/index.js +1 -0
  103. package/lib/esm/workouts/calendar/sync/trainerday/provider.js +139 -0
  104. package/lib/esm/workouts/calendar/sync/trainingpeaks/provider.js +26 -101
  105. package/lib/types/activities/ride/index.d.ts +1 -0
  106. package/lib/types/activities/ride/service.d.ts +16 -4
  107. package/lib/types/activities/ride/types.d.ts +13 -0
  108. package/lib/types/activities/upload/index.d.ts +1 -0
  109. package/lib/types/activities/upload/trainerday.d.ts +32 -0
  110. package/lib/types/activities/upload/types.d.ts +1 -0
  111. package/lib/types/apps/base/api/index.d.ts +1 -0
  112. package/lib/types/apps/base/api/oauth.d.ts +29 -0
  113. package/lib/types/apps/base/api/trainerday/api.d.ts +9 -0
  114. package/lib/types/apps/base/api/trainerday/index.d.ts +2 -0
  115. package/lib/types/apps/base/api/trainerday/types.d.ts +62 -0
  116. package/lib/types/apps/base/api/trainerday/utils.d.ts +13 -0
  117. package/lib/types/apps/base/api/trainingpeaks/api.d.ts +2 -24
  118. package/lib/types/apps/base/api/trainingpeaks/types.d.ts +3 -13
  119. package/lib/types/apps/base/api/types.d.ts +20 -0
  120. package/lib/types/apps/base/utils.d.ts +7 -0
  121. package/lib/types/apps/index.d.ts +1 -0
  122. package/lib/types/apps/trainerday/TrainerDayAppConnection.d.ts +13 -0
  123. package/lib/types/apps/trainerday/index.d.ts +2 -0
  124. package/lib/types/apps/trainerday/types.d.ts +2 -0
  125. package/lib/types/apps/types.d.ts +1 -0
  126. package/lib/types/base/dialogs/index.d.ts +2 -0
  127. package/lib/types/base/dialogs/service.d.ts +15 -0
  128. package/lib/types/base/dialogs/types.d.ts +6 -0
  129. package/lib/types/ride/display/service.d.ts +1 -1
  130. package/lib/types/settings/dialog/index.d.ts +1 -0
  131. package/lib/types/settings/dialog/support/base/service.d.ts +22 -0
  132. package/lib/types/settings/dialog/support/base/types.d.ts +61 -0
  133. package/lib/types/settings/dialog/support/desktop/service.d.ts +6 -0
  134. package/lib/types/settings/dialog/support/index.d.ts +7 -0
  135. package/lib/types/settings/dialog/support/mobile/service.d.ts +6 -0
  136. package/lib/types/settings/dialog/support/types.d.ts +1 -0
  137. package/lib/types/settings/display/support/dialog-types.d.ts +61 -0
  138. package/lib/types/settings/display/support/index.d.ts +1 -0
  139. package/lib/types/settings/display/support/service.d.ts +11 -1
  140. package/lib/types/settings/display/support/types.d.ts +59 -0
  141. package/lib/types/settings/page/index.d.ts +1 -0
  142. package/lib/types/settings/page/support/base/service.d.ts +25 -0
  143. package/lib/types/settings/page/support/base/types.d.ts +68 -0
  144. package/lib/types/settings/page/support/desktop/service.d.ts +6 -0
  145. package/lib/types/settings/page/support/index.d.ts +7 -0
  146. package/lib/types/settings/page/support/mobile/service.d.ts +6 -0
  147. package/lib/types/settings/page/support/types.d.ts +1 -0
  148. package/lib/types/settings/support/copy.d.ts +43 -0
  149. package/lib/types/settings/support/donation.d.ts +4 -0
  150. package/lib/types/settings/support/index.d.ts +3 -0
  151. package/lib/types/settings/support/mailto.d.ts +14 -0
  152. package/lib/types/settings/support/types.d.ts +9 -0
  153. package/lib/types/settings/support/urls.d.ts +9 -0
  154. package/lib/types/utils/base64.d.ts +4 -0
  155. package/lib/types/utils/index.d.ts +2 -0
  156. package/lib/types/utils/utf8.d.ts +4 -0
  157. package/lib/types/utils/xml.d.ts +1 -0
  158. package/lib/types/workouts/base/parsers/trainerday/converter.d.ts +7 -0
  159. package/lib/types/workouts/base/parsers/trainerday/types.d.ts +5 -0
  160. package/lib/types/workouts/calendar/sync/base/provider.d.ts +26 -0
  161. package/lib/types/workouts/calendar/sync/base/types.d.ts +3 -0
  162. package/lib/types/workouts/calendar/sync/index.d.ts +1 -0
  163. package/lib/types/workouts/calendar/sync/trainerday/provider.d.ts +19 -0
  164. package/lib/types/workouts/calendar/sync/trainingpeaks/provider.d.ts +7 -14
  165. package/package.json +1 -1
@@ -48,6 +48,8 @@ const incyclist_devices_1 = require("incyclist-devices");
48
48
  const devices_1 = require("../../devices");
49
49
  const base_1 = require("../base");
50
50
  const uuid_1 = require("uuid");
51
+ const copy_1 = require("../../settings/support/copy");
52
+ const donation_1 = require("../../settings/support/donation");
51
53
  const workouts_1 = require("../../workouts");
52
54
  const route_1 = require("../../routes/base/utils/route");
53
55
  const route_2 = require("../../routes/base/model/route");
@@ -64,6 +66,12 @@ const i18n_1 = require("../../i18n");
64
66
  const utils_3 = require("../list/utils");
65
67
  const sleep_1 = require("../../utils/sleep");
66
68
  const SAVE_INTERVAL = 5000;
69
+ const DAY = 24 * 60 * 60 * 1000;
70
+ const DONATE_CLICKED_PAUSE = 365 * DAY;
71
+ const DONATE_SHOWN_PAUSE = 30 * DAY;
72
+ const DONATE_MIN_TIME = 600;
73
+ const DONATE_MIN_DISTANCE = 2000;
74
+ const DONATE_MIN_ACTIVITIES = 10;
67
75
  let ActivityRideService = (() => {
68
76
  let _classDecorators = [types_1.Singleton];
69
77
  let _classDescriptor;
@@ -99,7 +107,7 @@ let ActivityRideService = (() => {
99
107
  prevEmit;
100
108
  saveObserver;
101
109
  isSaveDone;
102
- isDonateShown;
110
+ donateDecision;
103
111
  isSummaryShown;
104
112
  stopPromise;
105
113
  statsCalculator;
@@ -172,7 +180,7 @@ let ActivityRideService = (() => {
172
180
  this.tsStart = Date.now();
173
181
  this.tsPauseStart = undefined;
174
182
  this.isSaveDone = false;
175
- this.isDonateShown = false;
183
+ this.donateDecision = undefined;
176
184
  this.isSummaryShown = false;
177
185
  this.logEvent({ message: 'activity started', sport: this.activity.sport ?? 'cycling' });
178
186
  this.startWorker();
@@ -452,6 +460,7 @@ let ActivityRideService = (() => {
452
460
  this.logEvent({ message: 'activity summary shown', showSave, showContinue, showMap, showWorkoutSummary, fileLink: this.activity?.fitFileName });
453
461
  }
454
462
  this.isSummaryShown = true;
463
+ const donation = this.buildDonation();
455
464
  const props = {
456
465
  activity: (0, utils_3.createUIActivityDetails)(this.activity),
457
466
  showSave,
@@ -460,7 +469,8 @@ let ActivityRideService = (() => {
460
469
  showMap,
461
470
  showWorkoutSummary,
462
471
  workoutGraph,
463
- showDonate: this.canShowDonate(),
472
+ donation,
473
+ showDonate: !!donation,
464
474
  preview,
465
475
  units: this.getUnitConverter().getDefaultUnits()
466
476
  };
@@ -501,43 +511,72 @@ let ActivityRideService = (() => {
501
511
  }
502
512
  canShowDonate() {
503
513
  try {
504
- if (this.isDonateShown) {
505
- return true;
506
- }
507
- const trialGroup = 'A';
508
- if (this.saveObserver || this.isSaveDone || trialGroup === 'B') {
509
- const lastClicked = this.getUserSettings().getValue('state.donateClicked', 0);
510
- if (Date.now() - lastClicked < 1000 * 60 * 60 * 24 * 365) {
511
- if (this.saveObserver)
512
- this.logEvent({ message: 'donate check ', showDonate: false, lastClicked: new Date(lastClicked).toISOString() });
513
- return false;
514
- }
515
- const lastShown = this.getUserSettings().getValue('state.donateShown', 0);
516
- if (Date.now() - lastShown < 1000 * 60 * 60 * 24 * 14) {
517
- if (this.saveObserver)
518
- this.logEvent({ message: 'donate check ', showDonate: false, lastClicked: new Date(lastShown).toISOString() });
519
- return false;
520
- }
521
- const activities = this.getRepo().getAll();
522
- const lastYear = new Date();
523
- lastYear.setFullYear(lastYear.getFullYear() - 1);
524
- const activitiesLastYear = activities.filter(a => a.summary?.startTime > lastYear.getTime() && a.summary?.distance > 2000);
525
- if (this.saveObserver)
526
- this.logEvent({ message: 'donate check ', trialGroup, showDonate: activitiesLastYear?.length >= 10, activities: activitiesLastYear?.length });
527
- if (activitiesLastYear.length < 10)
528
- return false;
529
- this.getUserSettings().set('state.donateShown', Date.now());
530
- this.isDonateShown = true;
531
- return true;
532
- }
514
+ if (this.donateDecision !== undefined)
515
+ return this.donateDecision;
516
+ const mode = (0, donation_1.getDonationMode)();
517
+ if (mode === 'website')
518
+ return this.setDonateDecision(false, { mode, reason: 'website-mode' });
519
+ if (!this.isSaveDone)
520
+ return undefined;
521
+ const { reason, activities } = this.getDonateBlockReason();
522
+ if (reason)
523
+ return this.setDonateDecision(false, { mode, reason, activities });
524
+ this.getUserSettings().set('state.donateShown', Date.now());
525
+ this.logEvent({ message: 'donate shown', mode, activities });
526
+ return this.setDonateDecision(true, { mode, activities });
533
527
  }
534
528
  catch (err) {
535
529
  this.logError(err, 'canShowDonate');
536
530
  }
537
531
  return false;
538
532
  }
539
- onDonateClicked() {
533
+ setDonateDecision(showDonate, info) {
534
+ this.donateDecision = showDonate;
535
+ const event = { message: 'donate check', showDonate, mode: info.mode };
536
+ if (info.reason !== undefined)
537
+ event.reason = info.reason;
538
+ if (info.activities !== undefined)
539
+ event.activities = info.activities;
540
+ this.logEvent(event);
541
+ return showDonate;
542
+ }
543
+ getDonateBlockReason() {
544
+ const settings = this.getUserSettings();
545
+ const now = Date.now();
546
+ if (settings.getValue('state.donateHidden', 0))
547
+ return { reason: 'hidden' };
548
+ if (now - settings.getValue('state.donateClicked', 0) < DONATE_CLICKED_PAUSE)
549
+ return { reason: 'clicked' };
550
+ if (now - settings.getValue('state.donateShown', 0) < DONATE_SHOWN_PAUSE)
551
+ return { reason: 'recently-shown' };
552
+ if ((this.activity?.time ?? 0) < DONATE_MIN_TIME || (this.activity?.distance ?? 0) < DONATE_MIN_DISTANCE)
553
+ return { reason: 'short-ride' };
554
+ const lastYear = new Date();
555
+ lastYear.setFullYear(lastYear.getFullYear() - 1);
556
+ const activities = this.getRepo().getAll()
557
+ .filter(a => a.summary?.startTime > lastYear.getTime() && a.summary?.distance > DONATE_MIN_DISTANCE).length;
558
+ if (activities < DONATE_MIN_ACTIVITIES)
559
+ return { reason: 'usage', activities };
560
+ return { activities };
561
+ }
562
+ buildDonation() {
563
+ if (this.canShowDonate() !== true)
564
+ return undefined;
565
+ return {
566
+ text: copy_1.COPY.summaryText,
567
+ shortText: copy_1.COPY.summaryShortText,
568
+ links: (0, donation_1.getDonationChannels)().map(c => ({ id: c.id, label: c.label, url: c.url })),
569
+ hideLabel: copy_1.COPY.hideLabel,
570
+ };
571
+ }
572
+ onDonateClicked(channelId) {
540
573
  this.getUserSettings().set('state.donateClicked', Date.now());
574
+ this.logEvent({ message: 'donate clicked', donationChannel: channelId ?? 'unknown', source: 'summary' });
575
+ }
576
+ onDonateHidden() {
577
+ this.getUserSettings().set('state.donateHidden', Date.now());
578
+ this.donateDecision = false;
579
+ this.logEvent({ message: 'donate hidden', source: 'summary' });
541
580
  }
542
581
  getActivity() {
543
582
  return this.activity;
@@ -18,5 +18,6 @@ __exportStar(require("./strava"), exports);
18
18
  __exportStar(require("./intervals"), exports);
19
19
  __exportStar(require("./komoot"), exports);
20
20
  __exportStar(require("./trainingpeaks"), exports);
21
+ __exportStar(require("./trainerday"), exports);
21
22
  __exportStar(require("./types"), exports);
22
23
  __exportStar(require("./factory"), exports);
@@ -0,0 +1,216 @@
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.TrainerDayUpload = exports.TRAINERDAY_ACTIVITY_URL = void 0;
38
+ const api_1 = require("../../api");
39
+ const TrainerDayAppConnection_1 = require("../../apps/trainerday/TrainerDayAppConnection");
40
+ const Injection_1 = require("../../base/decorators/Injection");
41
+ const service_1 = require("../../base/service");
42
+ const types_1 = require("../../base/types");
43
+ const factory_1 = require("./factory");
44
+ const base64_1 = require("../../utils/base64");
45
+ const utf8_1 = require("../../utils/utf8");
46
+ exports.TRAINERDAY_ACTIVITY_URL = 'https://app.trainerday.com/activities';
47
+ const SUPPORTED_FORMATS = new Set(['tcx', 'fit']);
48
+ let TrainerDayUpload = (() => {
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 _getTrainerDayAppConnection_decorators;
56
+ let _getFileSystem_decorators;
57
+ var TrainerDayUpload = 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
+ _getTrainerDayAppConnection_decorators = [Injection_1.Injectable];
62
+ _getFileSystem_decorators = [Injection_1.Injectable];
63
+ __esDecorate(this, null, _getTrainerDayAppConnection_decorators, { kind: "method", name: "getTrainerDayAppConnection", static: false, private: false, access: { has: obj => "getTrainerDayAppConnection" in obj, get: obj => obj.getTrainerDayAppConnection }, 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
+ TrainerDayUpload = _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 TrainerDayAppConnection_1.TrainerDayAppConnection();
72
+ constructor() {
73
+ super('TrainerDayUpload');
74
+ this.isInitialized = false;
75
+ this.init();
76
+ }
77
+ init() {
78
+ if (this.isInitialized)
79
+ return true;
80
+ this.isInitialized = this.getTrainerDayAppConnection().init();
81
+ return this.isInitialized;
82
+ }
83
+ isConnected() {
84
+ return this.getTrainerDayAppConnection().isConnected();
85
+ }
86
+ async upload(activity, format = 'TCX') {
87
+ if (!this.ensureInitialized()) {
88
+ this.logEvent({ message: 'TrainerDay 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: 'TrainerDay Upload', format: lcFormat.toUpperCase() });
96
+ const dataType = this.getDataType(lcFormat);
97
+ const fileName = this.getActivityFile(activity, lcFormat);
98
+ const data = await this.readFile(fileName, dataType);
99
+ const res = await this.getApi().uploadActivity({
100
+ name: this.getName(activity),
101
+ dataType,
102
+ data,
103
+ externalId: activity.id,
104
+ sportType: activity.sport === 'rowing' ? undefined : 'bike'
105
+ });
106
+ const activityId = res?.activityId === undefined || res.activityId === null ? '' : String(res.activityId);
107
+ if (!activityId)
108
+ throw new Error('TrainerDay did not return an activity id');
109
+ this.logEvent({ message: 'TrainerDay Upload success', activityId });
110
+ this.setLink(activity, { activity_id: activityId, url: this.getUrl(activityId) });
111
+ return true;
112
+ }
113
+ catch (err) {
114
+ const error = err?.message ?? String(err);
115
+ this.logEvent({ message: 'TrainerDay Upload failure', error });
116
+ this.setLink(activity, { error });
117
+ return false;
118
+ }
119
+ }
120
+ getUrl(activityId) {
121
+ return `${exports.TRAINERDAY_ACTIVITY_URL}/${activityId}`;
122
+ }
123
+ getDataType(format) {
124
+ if (!SUPPORTED_FORMATS.has(format))
125
+ throw new Error(`format ${format.toUpperCase()} is not supported by TrainerDay`);
126
+ return format;
127
+ }
128
+ getActivityFile(activity, format) {
129
+ const fileName = activity[`${format}FileName`];
130
+ if (!fileName)
131
+ throw new Error(`no ${format.toUpperCase()} file available for this activity`);
132
+ return fileName;
133
+ }
134
+ getName(activity) {
135
+ const title = activity.title?.trim();
136
+ if (title)
137
+ return title;
138
+ const routeName = (activity.route?.title ?? activity.route?.name)?.trim();
139
+ if (routeName)
140
+ return routeName;
141
+ const start = new Date(activity.startTime);
142
+ return Number.isNaN(start.valueOf()) ? 'Incyclist ride' : `Incyclist ride ${start.toISOString().substring(0, 10)}`;
143
+ }
144
+ async readFile(fileName, format) {
145
+ const fs = this.getFileSystem();
146
+ if (!(await fs.existsFile(fileName)))
147
+ throw new Error('activity file not found');
148
+ const content = await fs.readFile(fileName, 'base64');
149
+ if (!content)
150
+ throw new Error('activity file is empty');
151
+ const contentType = this.getContentType(content);
152
+ const data = this.toData(content, format);
153
+ const isXml = format === 'fit' ? undefined : this.isXml(data);
154
+ this.logEvent({ message: 'TrainerDay Upload file', contentType, bytes: this.getSize(data), isXml });
155
+ if (isXml === false)
156
+ throw new Error(`activity file does not contain xml (content type: ${contentType})`);
157
+ return data;
158
+ }
159
+ getContentType(content) {
160
+ if (typeof content !== 'object' || content === null)
161
+ return typeof content;
162
+ return content.constructor?.name ?? 'object';
163
+ }
164
+ toData(content, format) {
165
+ if (typeof content === 'string') {
166
+ const compact = content.replaceAll(/\s/g, '');
167
+ if (compact.length % 4 === 0 && (0, base64_1.isBase64)(compact))
168
+ return compact;
169
+ if (format === 'fit')
170
+ throw new Error('binary file could not be read');
171
+ return new TextEncoder().encode(content);
172
+ }
173
+ return this.toBytes(content);
174
+ }
175
+ toBytes(content) {
176
+ if (ArrayBuffer.isView(content))
177
+ return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
178
+ if (content instanceof ArrayBuffer)
179
+ return new Uint8Array(content);
180
+ const serialized = content;
181
+ if (serialized?.type === 'Buffer' && Array.isArray(serialized.data))
182
+ return Uint8Array.from(serialized.data);
183
+ throw new Error('activity file has an unsupported content type');
184
+ }
185
+ getSize(data) {
186
+ return typeof data === 'string' ? (0, base64_1.base64Size)(data) : data.byteLength;
187
+ }
188
+ isXml(data) {
189
+ const head = typeof data === 'string'
190
+ ? (0, base64_1.fromBase64)(data.substring(0, 88))
191
+ : data.subarray(0, 66);
192
+ return (0, utf8_1.utf8Decode)(head).replace(/^\u{FEFF}/u, '').trimStart().startsWith('<');
193
+ }
194
+ setLink(activity, link) {
195
+ activity.links = { ...activity.links, trainerday: link };
196
+ }
197
+ ensureInitialized() {
198
+ if (!this.isInitialized)
199
+ this.init();
200
+ return this.isInitialized;
201
+ }
202
+ getTrainerDayAppConnection() {
203
+ return this.connection;
204
+ }
205
+ getFileSystem() {
206
+ return (0, api_1.getBindings)().fs;
207
+ }
208
+ getApi() {
209
+ return this.getTrainerDayAppConnection().getApi();
210
+ }
211
+ };
212
+ return TrainerDayUpload = _classThis;
213
+ })();
214
+ exports.TrainerDayUpload = TrainerDayUpload;
215
+ const factory = new factory_1.ActivityUploadFactory();
216
+ factory.add('trainerday', new TrainerDayUpload());
@@ -41,7 +41,7 @@ const Injection_1 = require("../../base/decorators/Injection");
41
41
  const service_1 = require("../../base/service");
42
42
  const types_1 = require("../../base/types");
43
43
  const trainingpeaks_1 = require("../../apps/base/api/trainingpeaks");
44
- const utils_1 = require("../../apps/base/api/trainingpeaks/utils");
44
+ const base64_1 = require("../../utils/base64");
45
45
  const factory_1 = require("./factory");
46
46
  const SUPPORTED_FORMATS = new Set(['tcx', 'fit']);
47
47
  const EXISTING_ACTIVITY = 'existing';
@@ -168,7 +168,7 @@ let TrainingPeaksUpload = (() => {
168
168
  toBase64(content, format) {
169
169
  if (typeof content === 'string') {
170
170
  const compact = content.replaceAll(/\s/g, '');
171
- if ((0, utils_1.isBase64)(compact))
171
+ if ((0, base64_1.isBase64)(compact))
172
172
  return compact;
173
173
  if (format === 'fit')
174
174
  throw new Error('binary file could not be read');
@@ -19,3 +19,4 @@ __exportStar(require("./strava"), exports);
19
19
  __exportStar(require("./komoot"), exports);
20
20
  __exportStar(require("./intervals"), exports);
21
21
  __exportStar(require("./trainingpeaks"), exports);
22
+ __exportStar(require("./trainerday"), exports);
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAuthAppApiBase = 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 utils_1 = require("../utils");
8
+ const base_1 = require("./base");
9
+ const AUTH_SERVER_URL = 'https://auth.incyclist.com';
10
+ class OAuthAppApiBase extends base_1.AppApiBase {
11
+ props;
12
+ config;
13
+ logger;
14
+ observer;
15
+ refreshPromise;
16
+ constructor(loggerName, props) {
17
+ super();
18
+ this.props = props;
19
+ this.logger = new gd_eventlog_1.EventLogger(loggerName);
20
+ this.observer = new observer_1.Observer();
21
+ }
22
+ init(config) {
23
+ this.config = config;
24
+ return this.observer;
25
+ }
26
+ update(config) {
27
+ if (!this.config)
28
+ throw new Error('update not allowed before init');
29
+ this.config = { ...this.config, ...config };
30
+ }
31
+ isAuthenticated() {
32
+ return (0, valid_1.valid)(this.config?.accessToken);
33
+ }
34
+ async request(method, url, data, config) {
35
+ await this.verifyAuthentication();
36
+ const request = {
37
+ method,
38
+ url: this.getBaseUrl() + url,
39
+ data,
40
+ headers: {
41
+ Authorization: 'Bearer ' + this.config.accessToken
42
+ },
43
+ validateStatus: (status) => status >= 200 && status < 300,
44
+ ...config
45
+ };
46
+ return await this.getApi().request(request);
47
+ }
48
+ async get(url, config) {
49
+ return await this.request('get', url, undefined, config);
50
+ }
51
+ mapUploadRejection(err) {
52
+ const status = err.response?.status;
53
+ if (status) {
54
+ const detail = (0, utils_1.getErrorDetail)(err.response.data);
55
+ return new Error(`Upload rejected by ${this.props.name} (HTTP ${status})${detail ? ': ' + detail : ''}`);
56
+ }
57
+ return err;
58
+ }
59
+ async verifyAuthentication() {
60
+ if (!this.isAuthenticated())
61
+ throw new Error('not authenticated');
62
+ await this.verifyToken();
63
+ }
64
+ async verifyToken() {
65
+ if (this.isTokenStillValid())
66
+ return;
67
+ try {
68
+ await this.refreshTokenOnce();
69
+ }
70
+ catch {
71
+ throw new Error('token refresh failed');
72
+ }
73
+ }
74
+ refreshTokenOnce() {
75
+ this.refreshPromise ??= this.refreshToken().finally(() => { this.refreshPromise = undefined; });
76
+ return this.refreshPromise;
77
+ }
78
+ isTokenStillValid() {
79
+ const expiration = this.config?.expiration;
80
+ if (!expiration)
81
+ return false;
82
+ return Date.now() < expiration.valueOf();
83
+ }
84
+ async refreshToken() {
85
+ const { name, refreshPath } = this.props;
86
+ this.logger.logEvent({ message: `${name} refresh token start` });
87
+ const url = this.getAuthServerUrl() + refreshPath;
88
+ try {
89
+ const response = await this.getApi().request({
90
+ method: 'post',
91
+ url,
92
+ data: { refresh_token: this.config.refreshToken }
93
+ });
94
+ const data = response.data;
95
+ this.config.accessToken = data.access_token;
96
+ this.config.refreshToken = data.refresh_token;
97
+ this.config.expiration = this.getExpiration(data);
98
+ this.logger.logEvent({ message: `${name} refresh token result`, status: 'success' });
99
+ this.observer.emit('token.updated', this.config);
100
+ }
101
+ catch (err) {
102
+ const error = err.response ? `HTTP error ${err.response.status}: ${err.response.statusText}, url:${url}` : err.message;
103
+ this.logger.logEvent({ message: `${name} refresh token result`, status: 'error', error });
104
+ throw err;
105
+ }
106
+ }
107
+ getSetting(key, defValue) {
108
+ try {
109
+ const settings = this.getUserSettings();
110
+ if (settings?.isInitialized === false)
111
+ return defValue;
112
+ return settings.get(key, defValue) ?? defValue;
113
+ }
114
+ catch {
115
+ return defValue;
116
+ }
117
+ }
118
+ getAuthServerUrl() {
119
+ return this.getSetting(this.props.authUrlSetting, null)
120
+ ?? this.getSetting('oauthUrl', null)
121
+ ?? AUTH_SERVER_URL;
122
+ }
123
+ getBaseUrl() {
124
+ return this.getSetting(this.props.apiUrlSetting, this.props.defaultApiUrl) ?? this.props.defaultApiUrl;
125
+ }
126
+ getApi() {
127
+ return super.getApi(true);
128
+ }
129
+ }
130
+ exports.OAuthAppApiBase = OAuthAppApiBase;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrainerDayApi = void 0;
4
+ const xml_1 = require("../../../../utils/xml");
5
+ const oauth_1 = require("../oauth");
6
+ const base64_1 = require("../../../../utils/base64");
7
+ const utf8_1 = require("../../../../utils/utf8");
8
+ const utils_1 = require("../../utils");
9
+ const types_1 = require("./types");
10
+ class TrainerDayApi extends oauth_1.OAuthAppApiBase {
11
+ constructor() {
12
+ super('TrainerDayApi', {
13
+ name: 'TrainerDay',
14
+ refreshPath: '/trainerday/refresh',
15
+ defaultApiUrl: 'https://api.trainerday.com',
16
+ apiUrlSetting: 'TRAINERDAY_API',
17
+ authUrlSetting: 'TRAINERDAY_AUTH_SERVER_URL'
18
+ });
19
+ }
20
+ async getCalendar(startDate, endDate) {
21
+ const params = { startDate: (0, utils_1.formatDay)(startDate), endDate: (0, utils_1.formatDay)(endDate) };
22
+ const response = await this.get('/api/v2/calendar', { params });
23
+ if (!Array.isArray(response.data))
24
+ throw new Error('Unexpected response from TrainerDay calendar: expected an array');
25
+ return response.data;
26
+ }
27
+ async uploadActivity(props) {
28
+ const { name, dataType, externalId, sportType } = props;
29
+ const data = this.prepareData(props);
30
+ this.logger.logEvent({ message: 'TrainerDay upload', format: dataType, bytes: (0, base64_1.base64Size)(data) });
31
+ const body = { name, dataType, data, externalId, sportType };
32
+ let response;
33
+ try {
34
+ response = await this.request('post', '/api/v1/activities/upload', body);
35
+ }
36
+ catch (err) {
37
+ throw this.mapUploadRejection(err);
38
+ }
39
+ if (response.data?.duplicate === true) {
40
+ const activityId = response.data.id ?? response.data.activityId;
41
+ this.logger.logEvent({ message: 'TrainerDay upload duplicate', activityId });
42
+ return { activityId, duplicate: true };
43
+ }
44
+ return { activityId: response.data?.activityId };
45
+ }
46
+ prepareData(props) {
47
+ const isXml = props.dataType === 'tcx' || props.dataType === 'gpx';
48
+ const bytes = typeof props.data === 'string' ? undefined : props.data;
49
+ if (!isXml)
50
+ return bytes ? (0, base64_1.toBase64)(bytes) : props.data;
51
+ const xml = (0, utf8_1.utf8Decode)(bytes ?? (0, base64_1.fromBase64)(props.data));
52
+ return (0, base64_1.toBase64)((0, utf8_1.utf8Encode)((0, xml_1.trimXmlTextNodes)(xml)));
53
+ }
54
+ getExpiration(data) {
55
+ return (0, utils_1.getTokenExpiration)(data, types_1.DEFAULT_TOKEN_LIFETIME_MS);
56
+ }
57
+ }
58
+ exports.TrainerDayApi = TrainerDayApi;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./api"), exports);
18
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TOKEN_LIFETIME_MS = void 0;
4
+ exports.DEFAULT_TOKEN_LIFETIME_MS = 6 * 60 * 60 * 1000;