incyclist-services 1.9.31 → 1.9.33

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 (175) hide show
  1. package/README.MD +72 -0
  2. package/lib/cjs/activities/upload/index.js +1 -0
  3. package/lib/cjs/activities/upload/komoot.js +2 -2
  4. package/lib/cjs/activities/upload/ridewithgps.js +158 -0
  5. package/lib/cjs/api/rest/api.js +109 -4
  6. package/lib/cjs/api/rest/types.js +2 -0
  7. package/lib/cjs/apps/base/api/index.js +1 -0
  8. package/lib/cjs/apps/base/api/oauth.js +45 -5
  9. package/lib/cjs/apps/base/api/ridewithgps/api.js +129 -0
  10. package/lib/cjs/apps/base/api/ridewithgps/index.js +19 -0
  11. package/lib/cjs/apps/base/api/ridewithgps/types.js +18 -0
  12. package/lib/cjs/apps/base/api/ridewithgps/utils.js +42 -0
  13. package/lib/cjs/apps/base/app/OAuthAppConnection.js +21 -4
  14. package/lib/cjs/apps/index.js +1 -0
  15. package/lib/cjs/apps/ridewithgps/RideWithGpsAppConnection.js +83 -0
  16. package/lib/cjs/apps/ridewithgps/index.js +18 -0
  17. package/lib/cjs/apps/ridewithgps/types.js +2 -0
  18. package/lib/cjs/apps/service.js +14 -1
  19. package/lib/cjs/coaches/coach.js +14 -6
  20. package/lib/cjs/devices/ride/service.js +42 -0
  21. package/lib/cjs/ride/base/base.js +14 -0
  22. package/lib/cjs/ride/route/RLVDisplayService.js +18 -4
  23. package/lib/cjs/routes/base/api/api.js +11 -2
  24. package/lib/cjs/routes/base/api/factory.js +12 -2
  25. package/lib/cjs/routes/base/api/unconfigured.js +24 -0
  26. package/lib/cjs/routes/base/parsers/utils.js +12 -1
  27. package/lib/cjs/routes/index.js +1 -0
  28. package/lib/cjs/routes/list/cards/RouteCard.js +9 -10
  29. package/lib/cjs/routes/list/loaders/api.js +194 -40
  30. package/lib/cjs/routes/list/service.js +217 -26
  31. package/lib/cjs/routes/servers/errors.js +14 -0
  32. package/lib/cjs/routes/servers/index.js +15 -0
  33. package/lib/cjs/routes/servers/known-servers.json +1 -0
  34. package/lib/cjs/routes/servers/known.js +11 -0
  35. package/lib/cjs/routes/servers/messages.js +35 -0
  36. package/lib/cjs/routes/servers/page/base/service.js +708 -0
  37. package/lib/cjs/routes/servers/page/base/types.js +2 -0
  38. package/lib/cjs/routes/servers/page/base/utils.js +34 -0
  39. package/lib/cjs/routes/servers/page/desktop/service.js +10 -0
  40. package/lib/cjs/routes/servers/page/index.js +28 -0
  41. package/lib/cjs/routes/servers/page/mobile/service.js +69 -0
  42. package/lib/cjs/routes/servers/page/types.js +2 -0
  43. package/lib/cjs/routes/servers/probe.js +72 -0
  44. package/lib/cjs/routes/servers/status.js +97 -0
  45. package/lib/cjs/routes/servers/types.js +2 -0
  46. package/lib/cjs/routes/servers/validator.js +209 -0
  47. package/lib/cjs/routes/sync/base/provider.js +51 -9
  48. package/lib/cjs/routes/sync/index.js +1 -0
  49. package/lib/cjs/routes/sync/komoot/provider.js +1 -27
  50. package/lib/cjs/routes/sync/ridewithgps/provider.js +182 -0
  51. package/lib/cjs/routes/sync/strava/provider.js +1 -28
  52. package/lib/cjs/settings/display/index.js +1 -0
  53. package/lib/cjs/settings/display/routeservers/index.js +21 -0
  54. package/lib/cjs/settings/display/routeservers/service.js +709 -0
  55. package/lib/cjs/settings/display/routeservers/types.js +2 -0
  56. package/lib/cjs/settings/display/routeservers/utils.js +34 -0
  57. package/lib/cjs/utils/string.js +8 -1
  58. package/lib/cjs/video/VideoConversion.js +3 -0
  59. package/lib/esm/activities/upload/index.js +1 -0
  60. package/lib/esm/activities/upload/komoot.js +2 -2
  61. package/lib/esm/activities/upload/ridewithgps.js +155 -0
  62. package/lib/esm/api/rest/api.js +76 -1
  63. package/lib/esm/api/rest/types.js +1 -1
  64. package/lib/esm/apps/base/api/index.js +1 -0
  65. package/lib/esm/apps/base/api/oauth.js +45 -5
  66. package/lib/esm/apps/base/api/ridewithgps/api.js +125 -0
  67. package/lib/esm/apps/base/api/ridewithgps/index.js +3 -0
  68. package/lib/esm/apps/base/api/ridewithgps/types.js +12 -0
  69. package/lib/esm/apps/base/api/ridewithgps/utils.js +34 -0
  70. package/lib/esm/apps/base/app/OAuthAppConnection.js +21 -4
  71. package/lib/esm/apps/index.js +1 -0
  72. package/lib/esm/apps/ridewithgps/RideWithGpsAppConnection.js +80 -0
  73. package/lib/esm/apps/ridewithgps/index.js +2 -0
  74. package/lib/esm/apps/ridewithgps/types.js +1 -0
  75. package/lib/esm/apps/service.js +14 -1
  76. package/lib/esm/coaches/coach.js +14 -6
  77. package/lib/esm/devices/ride/service.js +42 -0
  78. package/lib/esm/ride/base/base.js +14 -0
  79. package/lib/esm/ride/route/RLVDisplayService.js +18 -4
  80. package/lib/esm/routes/base/api/api.js +18 -3
  81. package/lib/esm/routes/base/api/factory.js +11 -1
  82. package/lib/esm/routes/base/api/unconfigured.js +20 -0
  83. package/lib/esm/routes/base/parsers/utils.js +10 -0
  84. package/lib/esm/routes/index.js +1 -0
  85. package/lib/esm/routes/list/cards/RouteCard.js +3 -4
  86. package/lib/esm/routes/list/loaders/api.js +202 -39
  87. package/lib/esm/routes/list/service.js +211 -20
  88. package/lib/esm/routes/servers/errors.js +10 -0
  89. package/lib/esm/routes/servers/index.js +4 -0
  90. package/lib/esm/routes/servers/known-servers.json +1 -0
  91. package/lib/esm/routes/servers/known.js +4 -0
  92. package/lib/esm/routes/servers/messages.js +32 -0
  93. package/lib/esm/routes/servers/page/base/service.js +705 -0
  94. package/lib/esm/routes/servers/page/base/types.js +1 -0
  95. package/lib/esm/routes/servers/page/base/utils.js +29 -0
  96. package/lib/esm/routes/servers/page/desktop/service.js +6 -0
  97. package/lib/esm/routes/servers/page/index.js +19 -0
  98. package/lib/esm/routes/servers/page/mobile/service.js +66 -0
  99. package/lib/esm/routes/servers/page/types.js +1 -0
  100. package/lib/esm/routes/servers/probe.js +63 -0
  101. package/lib/esm/routes/servers/status.js +93 -0
  102. package/lib/esm/routes/servers/types.js +1 -0
  103. package/lib/esm/routes/servers/validator.js +199 -0
  104. package/lib/esm/routes/sync/base/provider.js +51 -9
  105. package/lib/esm/routes/sync/index.js +1 -0
  106. package/lib/esm/routes/sync/komoot/provider.js +1 -27
  107. package/lib/esm/routes/sync/ridewithgps/provider.js +178 -0
  108. package/lib/esm/routes/sync/strava/provider.js +1 -28
  109. package/lib/esm/settings/display/index.js +1 -0
  110. package/lib/esm/settings/display/routeservers/index.js +2 -0
  111. package/lib/esm/settings/display/routeservers/service.js +705 -0
  112. package/lib/esm/settings/display/routeservers/types.js +1 -0
  113. package/lib/esm/settings/display/routeservers/utils.js +29 -0
  114. package/lib/esm/utils/string.js +6 -0
  115. package/lib/esm/video/VideoConversion.js +3 -0
  116. package/lib/types/activities/upload/index.d.ts +1 -0
  117. package/lib/types/activities/upload/ridewithgps.d.ts +30 -0
  118. package/lib/types/api/fs/index.d.ts +3 -0
  119. package/lib/types/api/rest/api.d.ts +6 -1
  120. package/lib/types/api/rest/types.d.ts +7 -0
  121. package/lib/types/apps/base/api/index.d.ts +1 -0
  122. package/lib/types/apps/base/api/oauth.d.ts +7 -1
  123. package/lib/types/apps/base/api/ridewithgps/api.d.ts +18 -0
  124. package/lib/types/apps/base/api/ridewithgps/index.d.ts +3 -0
  125. package/lib/types/apps/base/api/ridewithgps/types.d.ts +104 -0
  126. package/lib/types/apps/base/api/ridewithgps/utils.d.ts +9 -0
  127. package/lib/types/apps/base/api/types.d.ts +3 -2
  128. package/lib/types/apps/base/app/OAuthAppConnection.d.ts +6 -1
  129. package/lib/types/apps/base/types.d.ts +1 -1
  130. package/lib/types/apps/index.d.ts +1 -0
  131. package/lib/types/apps/ridewithgps/RideWithGpsAppConnection.d.ts +13 -0
  132. package/lib/types/apps/ridewithgps/index.d.ts +2 -0
  133. package/lib/types/apps/ridewithgps/types.d.ts +2 -0
  134. package/lib/types/apps/service.d.ts +5 -0
  135. package/lib/types/apps/types.d.ts +1 -0
  136. package/lib/types/coaches/coach.d.ts +1 -0
  137. package/lib/types/devices/ride/service.d.ts +5 -1
  138. package/lib/types/ride/base/base.d.ts +1 -0
  139. package/lib/types/ride/base/types.d.ts +7 -0
  140. package/lib/types/ride/display/service.d.ts +1 -1
  141. package/lib/types/ride/route/RLVDisplayService.d.ts +3 -2
  142. package/lib/types/routes/base/api/api.d.ts +9 -0
  143. package/lib/types/routes/base/api/factory.d.ts +2 -0
  144. package/lib/types/routes/base/api/unconfigured.d.ts +10 -0
  145. package/lib/types/routes/base/parsers/utils.d.ts +1 -0
  146. package/lib/types/routes/index.d.ts +1 -0
  147. package/lib/types/routes/list/loaders/api.d.ts +35 -3
  148. package/lib/types/routes/list/service.d.ts +43 -2
  149. package/lib/types/routes/list/types.d.ts +1 -0
  150. package/lib/types/routes/servers/errors.d.ts +6 -0
  151. package/lib/types/routes/servers/index.d.ts +5 -0
  152. package/lib/types/routes/servers/known.d.ts +2 -0
  153. package/lib/types/routes/servers/messages.d.ts +31 -0
  154. package/lib/types/routes/servers/page/base/service.d.ts +103 -0
  155. package/lib/types/routes/servers/page/base/types.d.ts +77 -0
  156. package/lib/types/routes/servers/page/base/utils.d.ts +2 -0
  157. package/lib/types/routes/servers/page/desktop/service.d.ts +4 -0
  158. package/lib/types/routes/servers/page/index.d.ts +9 -0
  159. package/lib/types/routes/servers/page/mobile/service.d.ts +6 -0
  160. package/lib/types/routes/servers/page/types.d.ts +1 -0
  161. package/lib/types/routes/servers/probe.d.ts +7 -0
  162. package/lib/types/routes/servers/status.d.ts +15 -0
  163. package/lib/types/routes/servers/types.d.ts +56 -0
  164. package/lib/types/routes/servers/validator.d.ts +8 -0
  165. package/lib/types/routes/sync/base/provider.d.ts +5 -1
  166. package/lib/types/routes/sync/index.d.ts +1 -0
  167. package/lib/types/routes/sync/ridewithgps/provider.d.ts +41 -0
  168. package/lib/types/settings/display/index.d.ts +1 -0
  169. package/lib/types/settings/display/routeservers/index.d.ts +3 -0
  170. package/lib/types/settings/display/routeservers/service.d.ts +102 -0
  171. package/lib/types/settings/display/routeservers/types.d.ts +76 -0
  172. package/lib/types/settings/display/routeservers/utils.d.ts +2 -0
  173. package/lib/types/utils/string.d.ts +1 -0
  174. package/lib/types/video/VideoConversion.d.ts +1 -0
  175. package/package.json +2 -2
package/README.MD CHANGED
@@ -110,6 +110,78 @@ import { useDeviceConfiguration, initUserSettings } from 'incyclist-services'
110
110
 
111
111
  `useXXX()` returns a service singleton, and `initXXX()` initializes one where needed.
112
112
 
113
+ ## Route servers
114
+
115
+ Besides the built-in Incyclist route server, the app can load routes from additional route
116
+ servers. Each route remembers the server it came from, and that server's name is its *Source*
117
+ in the route list filter. A route supplied by an external server stays attributed to that
118
+ server: an Incyclist route with the same id will not replace it.
119
+
120
+ ### Adding a route server as a user
121
+
122
+ In the app, open **Settings › Routes** (or the **Import Routes** dialog) and choose
123
+ **Add route server**. Pick a server from the known list, or enter an address and a name:
124
+
125
+ - The address must be `https://`. Plain `http://` is accepted only for servers on your home
126
+ network (`localhost`, private IP addresses, `*.local` names and single-label names such as
127
+ `nas`), and not on devices that don't allow it (currently Android).
128
+ - The address is the plain base URL of the server: it must not contain a query string (`?...`).
129
+ - The name (up to 24 letters, numbers, spaces or dashes) is the label shown in the route list.
130
+ It must not clash with an existing source such as `Local`, `Incyclist` or a connected app.
131
+
132
+ The server is checked before it is saved. Servers are stored in the user settings under
133
+ `routes.servers.<name>`, so a server can also be added by hand in `settings.json`. Entries
134
+ written there are not validated by the app and keep loading as they are.
135
+
136
+ ### Adding a server to the known list (maintainers)
137
+
138
+ The known list is the data file [`src/routes/servers/known-servers.json`](./src/routes/servers/known-servers.json).
139
+ It ships empty. While it is empty, the add screen only offers manual entry. To list a server,
140
+ add an entry. No code change is needed:
141
+
142
+ ```json
143
+ [
144
+ {
145
+ "id": "alpine-video-club",
146
+ "name": "Alpine Videos",
147
+ "url": "https://videos.example.org/api/v1/routes",
148
+ "description": "Alps & Dolomites, 40+ climbs",
149
+ "operator": "Alpine Video Club"
150
+ }
151
+ ]
152
+ ```
153
+
154
+ | Field | Rules |
155
+ |---|---|
156
+ | `id` | Required, stable and unique. Used for logging. |
157
+ | `name` | Required. Same rules as a user-entered name (see above). Becomes the source name. |
158
+ | `url` | Required. `https://` only. The server's routes API base URL. |
159
+ | `description` | Required. One short line, about 40 characters. |
160
+ | `operator` | Optional. Shown as "by ...". |
161
+
162
+ Test the server against Incyclist before listing it. A unit test checks every entry against
163
+ the name and URL rules and for unique ids and URLs, so run `npm test -- src/routes/servers`
164
+ after editing the file. The list is part of the UI bundle, so a change reaches users with the
165
+ next bundle release.
166
+
167
+ ### What a route server must provide
168
+
169
+ A route server is a plain HTTPS service. Incyclist checks a server by requesting
170
+ `<base-url>?type=video`, which must answer with a JSON array of
171
+ [`RouteApiDescription`](./src/routes/base/api/types.ts#L11) objects. Route details are then
172
+ requested from `<base-url>/<route-id>`, which must answer with a
173
+ [`RouteApiDetail`](./src/routes/base/api/types.ts#L51). A reachable server that answers
174
+ something else, such as an HTML page or a 404, is rejected as "not a route server". Redirects
175
+ that would lead to a URL the app would not accept (for example from `https://` to `http://`)
176
+ are rejected too: a server on the internet can never send the app to a host on the home network.
177
+ Requests to a server are given up after 30 seconds. The server then counts as unreachable.
178
+ A route can only be updated by the server it belongs to: a server that offers the id of an
179
+ Incyclist route (or of a route of another server) does not replace it.
180
+
181
+ GPX routes are optional. The app also requests `<base-url>?type=route` for them, with the same
182
+ kind of response. A server that does not support this request is still loaded normally and keeps
183
+ its video routes.
184
+
113
185
  ## Using this library in your own app
114
186
 
115
187
  The library never calls platform APIs directly. File access, settings storage, secrets,
@@ -21,3 +21,4 @@ __exportStar(require("./trainingpeaks"), exports);
21
21
  __exportStar(require("./trainerday"), exports);
22
22
  __exportStar(require("./types"), exports);
23
23
  __exportStar(require("./factory"), exports);
24
+ __exportStar(require("./ridewithgps"), exports);
@@ -100,7 +100,7 @@ let KomootUpload = (() => {
100
100
  if (!data) {
101
101
  throw new Error(`file could not be read: ${fileName}`);
102
102
  }
103
- const res = await this.getApi().uploadTour(Buffer.from(data), uploadFormat, sport, activity.title);
103
+ const res = await this.getApi().uploadTour(typeof data === 'string' ? Buffer.from(data, 'base64') : Buffer.from(data), uploadFormat, sport, activity.title);
104
104
  this.logEvent({ message: 'Komoot Upload success', activityId: res.id });
105
105
  activity.links.komoot = {
106
106
  activity_id: res.id.toString(),
@@ -142,7 +142,7 @@ let KomootUpload = (() => {
142
142
  const exists = await fs.existsFile(fileName);
143
143
  if (!exists)
144
144
  return null;
145
- const content = await fs.readFile(fileName);
145
+ const content = await fs.readFile(fileName, 'base64');
146
146
  return content || null;
147
147
  }
148
148
  catch (err) {
@@ -0,0 +1,158 @@
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.RideWithGpsUpload = exports.RIDEWITHGPS_URL = void 0;
38
+ const ridewithgps_1 = require("../../apps/base/api/ridewithgps");
39
+ const RideWithGpsAppConnection_1 = require("../../apps/ridewithgps/RideWithGpsAppConnection");
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
+ exports.RIDEWITHGPS_URL = 'https://ridewithgps.com';
45
+ const FORMATS = ['tcx', 'fit'];
46
+ let RideWithGpsUpload = (() => {
47
+ let _classDecorators = [types_1.Singleton];
48
+ let _classDescriptor;
49
+ let _classExtraInitializers = [];
50
+ let _classThis;
51
+ let _classSuper = service_1.IncyclistService;
52
+ let _instanceExtraInitializers = [];
53
+ let _getRideWithGpsAppConnection_decorators;
54
+ var RideWithGpsUpload = class extends _classSuper {
55
+ static { _classThis = this; }
56
+ static {
57
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
58
+ _getRideWithGpsAppConnection_decorators = [Injection_1.Injectable];
59
+ __esDecorate(this, null, _getRideWithGpsAppConnection_decorators, { kind: "method", name: "getRideWithGpsAppConnection", static: false, private: false, access: { has: obj => "getRideWithGpsAppConnection" in obj, get: obj => obj.getRideWithGpsAppConnection }, metadata: _metadata }, null, _instanceExtraInitializers);
60
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
61
+ RideWithGpsUpload = _classThis = _classDescriptor.value;
62
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
63
+ __runInitializers(_classThis, _classExtraInitializers);
64
+ }
65
+ isInitialized = __runInitializers(this, _instanceExtraInitializers);
66
+ connection = new RideWithGpsAppConnection_1.RideWithGpsAppConnection();
67
+ constructor() {
68
+ super('RideWithGpsUpload');
69
+ this.isInitialized = false;
70
+ this.init();
71
+ }
72
+ init() {
73
+ if (this.isInitialized)
74
+ return true;
75
+ this.isInitialized = this.getRideWithGpsAppConnection().init();
76
+ return this.isInitialized;
77
+ }
78
+ isConnected() {
79
+ return this.getRideWithGpsAppConnection().isConnected();
80
+ }
81
+ async upload(activity, format = 'TCX') {
82
+ if (!this.ensureInitialized()) {
83
+ this.logEvent({ message: 'RideWithGPS Upload skipped', reason: 'not initialized' });
84
+ return false;
85
+ }
86
+ if (!this.isConnected())
87
+ return false;
88
+ try {
89
+ const res = await this.uploadFirstAccepted(activity, format.toLowerCase());
90
+ this.logEvent({ message: 'RideWithGPS Upload success', activityId: res.tripId, duplicate: res.duplicate });
91
+ this.setLink(activity, this.buildLink(res));
92
+ return true;
93
+ }
94
+ catch (err) {
95
+ const error = err?.message ?? String(err);
96
+ this.logEvent({ message: 'RideWithGPS Upload failure', error });
97
+ this.setLink(activity, { error });
98
+ return false;
99
+ }
100
+ }
101
+ getUrl(activityId) {
102
+ return `${exports.RIDEWITHGPS_URL}/trips/${activityId}`;
103
+ }
104
+ async uploadFirstAccepted(activity, preferred) {
105
+ const formats = [preferred, ...FORMATS.filter(f => f !== preferred)].filter(f => FORMATS.includes(f) && activity[`${f}FileName`]);
106
+ if (formats.length === 0)
107
+ throw new Error('no TCX or FIT file available for this activity');
108
+ let lastError;
109
+ for (const format of formats) {
110
+ try {
111
+ this.logEvent({ message: 'RideWithGPS Upload', format: format.toUpperCase() });
112
+ return await this.getApi().uploadActivity({
113
+ fileName: activity[`${format}FileName`],
114
+ name: activity.title?.trim() || undefined,
115
+ activityType: this.getActivityType(activity)
116
+ });
117
+ }
118
+ catch (err) {
119
+ if (this.isFinal(err))
120
+ throw err;
121
+ this.logEvent({ message: 'RideWithGPS Upload not accepted', format: format.toUpperCase(), error: err.message });
122
+ lastError = err;
123
+ }
124
+ }
125
+ throw lastError;
126
+ }
127
+ isFinal(err) {
128
+ return err instanceof ridewithgps_1.RideWithGpsTimeDataMissingError || err instanceof ridewithgps_1.RideWithGpsAuthError || err instanceof ridewithgps_1.RideWithGpsTimeoutError;
129
+ }
130
+ getActivityType(activity) {
131
+ const isFreeRide = activity.routeType === 'Free-Ride' || activity.routeType === 'None';
132
+ return isFreeRide ? 'cycling:indoor' : 'cycling:virtual';
133
+ }
134
+ buildLink(res) {
135
+ if (res.tripId)
136
+ return { activity_id: res.tripId, url: this.getUrl(res.tripId) };
137
+ return { activity_id: 'existing', url: `${exports.RIDEWITHGPS_URL}/trips` };
138
+ }
139
+ setLink(activity, link) {
140
+ activity.links = { ...activity.links, ridewithgps: link };
141
+ }
142
+ ensureInitialized() {
143
+ if (!this.isInitialized)
144
+ this.init();
145
+ return this.isInitialized;
146
+ }
147
+ getRideWithGpsAppConnection() {
148
+ return this.connection;
149
+ }
150
+ getApi() {
151
+ return this.getRideWithGpsAppConnection().getApi();
152
+ }
153
+ };
154
+ return RideWithGpsUpload = _classThis;
155
+ })();
156
+ exports.RideWithGpsUpload = RideWithGpsUpload;
157
+ const factory = new factory_1.ActivityUploadFactory();
158
+ factory.add('ridewithgps', new RideWithGpsUpload());
@@ -1,16 +1,69 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
5
35
  Object.defineProperty(exports, "__esModule", { value: true });
6
36
  exports.ApiClient = void 0;
7
- const axios_1 = __importDefault(require("axios"));
37
+ const axios_1 = __importStar(require("axios"));
8
38
  const gd_eventlog_1 = require("gd-eventlog");
9
39
  const uuid_1 = require("uuid");
40
+ const types_1 = require("./types");
41
+ const getResponseUrl = (res) => {
42
+ return res?.request?.res?.responseUrl ?? res?.request?.responseURL;
43
+ };
44
+ const getRequestUrl = (config) => {
45
+ try {
46
+ return axios_1.default.getUri(config);
47
+ }
48
+ catch {
49
+ return config.url;
50
+ }
51
+ };
52
+ const getRedirectUrl = (options) => {
53
+ if (typeof options?.href === 'string')
54
+ return options.href;
55
+ if (!options?.protocol || !(options.host ?? options.hostname))
56
+ return undefined;
57
+ return `${options.protocol}//${options.host ?? options.hostname}${options.path ?? ''}`;
58
+ };
59
+ const redirectNotAllowed = (message, config, request, response) => {
60
+ return new axios_1.AxiosError(message, types_1.REDIRECT_NOT_ALLOWED, config, request, response);
61
+ };
10
62
  class ApiClient {
11
63
  axios;
12
64
  logger;
13
65
  requests;
66
+ redirectSkipLogged = false;
14
67
  requestInterceptorId;
15
68
  responseInterceptorId;
16
69
  constructor() {
@@ -34,10 +87,62 @@ class ApiClient {
34
87
  headers['X-API-Key'] = props['apiKey'];
35
88
  }
36
89
  this.axios = axios_1.default.create({ headers });
90
+ this.registerRedirectPolicy(this.axios);
37
91
  if (requestLog) {
38
92
  this.enableLogging();
39
93
  }
40
94
  }
95
+ registerRedirectPolicy(client) {
96
+ client.interceptors.request.use((config) => this.onRedirectPolicyRequest(config));
97
+ client.interceptors.response.use((res) => this.onRedirectPolicyResponse(res), (err) => this.onRedirectPolicyError(err));
98
+ }
99
+ onRedirectPolicyRequest(config) {
100
+ const policy = config?.redirectPolicy;
101
+ if (!policy)
102
+ return config;
103
+ const origin = getRequestUrl(config);
104
+ const previous = config.beforeRedirect;
105
+ config.beforeRedirect = (options, responseDetails, requestDetails) => {
106
+ previous?.(options, responseDetails, requestDetails);
107
+ const target = getRedirectUrl(options);
108
+ if (target && !policy(target, origin)) {
109
+ this.logger.logEvent({ message: 'redirect refused', stage: 'before redirect' });
110
+ throw redirectNotAllowed('redirect not allowed', config);
111
+ }
112
+ };
113
+ return config;
114
+ }
115
+ onRedirectPolicyResponse(res) {
116
+ const config = res?.config;
117
+ const policy = config?.redirectPolicy;
118
+ if (!policy)
119
+ return res;
120
+ const origin = getRequestUrl(config);
121
+ const finalUrl = getResponseUrl(res);
122
+ if (!finalUrl) {
123
+ if (!this.redirectSkipLogged) {
124
+ this.redirectSkipLogged = true;
125
+ this.logger.logEvent({ message: 'redirect check skipped', reason: 'final url not available' });
126
+ }
127
+ return res;
128
+ }
129
+ if (finalUrl === origin)
130
+ return res;
131
+ if (!policy(finalUrl, origin)) {
132
+ this.logger.logEvent({ message: 'redirect refused', stage: 'response' });
133
+ throw redirectNotAllowed('redirect not allowed', config, res.request, res);
134
+ }
135
+ return res;
136
+ }
137
+ onRedirectPolicyError(err) {
138
+ let cause = err?.cause;
139
+ for (let depth = 0; cause && depth < 5 && err?.code !== types_1.REDIRECT_NOT_ALLOWED; depth++) {
140
+ if (cause.code === types_1.REDIRECT_NOT_ALLOWED)
141
+ err.code = types_1.REDIRECT_NOT_ALLOWED;
142
+ cause = cause.cause;
143
+ }
144
+ return Promise.reject(err);
145
+ }
41
146
  enableLogging() {
42
147
  const client = this.client();
43
148
  if (this.requestInterceptorId !== undefined)
@@ -1,2 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDIRECT_NOT_ALLOWED = void 0;
4
+ exports.REDIRECT_NOT_ALLOWED = 'ERR_REDIRECT_NOT_ALLOWED';
@@ -20,3 +20,4 @@ __exportStar(require("./komoot"), exports);
20
20
  __exportStar(require("./intervals"), exports);
21
21
  __exportStar(require("./trainingpeaks"), exports);
22
22
  __exportStar(require("./trainerday"), exports);
23
+ __exportStar(require("./ridewithgps"), exports);
@@ -12,6 +12,7 @@ class OAuthAppApiBase extends base_1.AppApiBase {
12
12
  config;
13
13
  logger;
14
14
  observer;
15
+ authFailed = false;
15
16
  refreshPromise;
16
17
  constructor(loggerName, props) {
17
18
  super();
@@ -21,33 +22,70 @@ class OAuthAppApiBase extends base_1.AppApiBase {
21
22
  }
22
23
  init(config) {
23
24
  this.config = config;
25
+ if (config)
26
+ this.authFailed = false;
24
27
  return this.observer;
25
28
  }
26
29
  update(config) {
27
30
  if (!this.config)
28
31
  throw new Error('update not allowed before init');
29
32
  this.config = { ...this.config, ...config };
33
+ this.authFailed = false;
30
34
  }
31
35
  isAuthenticated() {
32
36
  return (0, valid_1.valid)(this.config?.accessToken);
33
37
  }
34
- async request(method, url, data, config) {
38
+ async request(method, url, data, config, options = {}) {
35
39
  await this.verifyAuthentication();
36
40
  const request = {
37
41
  method,
38
42
  url: this.getBaseUrl() + url,
39
43
  data,
40
- headers: {
41
- Authorization: 'Bearer ' + this.config.accessToken
42
- },
44
+ headers: this.getAuthHeaders(),
43
45
  validateStatus: (status) => status >= 200 && status < 300,
44
46
  ...config
45
47
  };
46
- return await this.getApi().request(request);
48
+ try {
49
+ return await this.getApi().request(request);
50
+ }
51
+ catch (err) {
52
+ if (options.checkRevoked !== false)
53
+ await this.checkRevoked(err);
54
+ throw err;
55
+ }
56
+ }
57
+ async checkRevoked(err) {
58
+ const { refreshPath, authCheckPath, name } = this.props;
59
+ if (refreshPath || !authCheckPath || this.authFailed || err?.response?.status !== 401)
60
+ return;
61
+ if (!(await this.isTokenRejected(authCheckPath)) || this.authFailed)
62
+ return;
63
+ this.authFailed = true;
64
+ this.logger.logEvent({ message: `${name} access token rejected`, status: 'error', error: 'HTTP 401, reconnect required' });
65
+ this.observer.emit('auth.failed', name);
66
+ }
67
+ async isTokenRejected(path) {
68
+ try {
69
+ await this.getApi().request({
70
+ method: 'get',
71
+ url: this.getBaseUrl() + path,
72
+ headers: this.getAuthHeaders(),
73
+ validateStatus: (status) => status >= 200 && status < 300
74
+ });
75
+ return false;
76
+ }
77
+ catch (err) {
78
+ return err?.response?.status === 401;
79
+ }
47
80
  }
48
81
  async get(url, config) {
49
82
  return await this.request('get', url, undefined, config);
50
83
  }
84
+ getAuthHeaders() {
85
+ if (!this.config?.accessToken)
86
+ throw new Error('not authenticated');
87
+ return { Authorization: 'Bearer ' + this.config.accessToken };
88
+ }
51
89
  mapUploadRejection(err) {
52
90
  const status = err.response?.status;
53
91
  if (status) {
@@ -76,6 +114,8 @@ class OAuthAppApiBase extends base_1.AppApiBase {
76
114
  return this.refreshPromise;
77
115
  }
78
116
  isTokenStillValid() {
117
+ if (!this.props.refreshPath)
118
+ return true;
79
119
  const expiration = this.config?.expiration;
80
120
  if (!expiration)
81
121
  return false;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RideWithGpsApi = void 0;
4
+ const sleep_1 = require("../../../../utils/sleep");
5
+ const oauth_1 = require("../oauth");
6
+ const types_1 = require("./types");
7
+ const utils_1 = require("./utils");
8
+ const POLL_INTERVAL_MS = 1000;
9
+ const MAX_POLLS = 60;
10
+ class RideWithGpsApi extends oauth_1.OAuthAppApiBase {
11
+ constructor() {
12
+ super('RideWithGpsApi', {
13
+ name: 'RideWithGPS',
14
+ defaultApiUrl: 'https://ridewithgps.com',
15
+ authCheckPath: '/api/v1/users/current.json',
16
+ apiUrlSetting: 'RWGPS_API',
17
+ authUrlSetting: 'RWGPS_AUTH_SERVER_URL'
18
+ });
19
+ }
20
+ async getRoutes(props = {}) {
21
+ const params = {};
22
+ if (props.page !== undefined)
23
+ params.page = props.page;
24
+ if (props.pageSize !== undefined)
25
+ params.page_size = props.pageSize;
26
+ if (props.archived !== undefined)
27
+ params.archived = String(props.archived);
28
+ const response = await this.get('/api/v1/routes.json', { params });
29
+ if (!Array.isArray(response.data?.routes))
30
+ throw new Error('Unexpected response from RideWithGPS routes: expected a list of routes');
31
+ return { routes: response.data.routes, pagination: response.data.meta?.pagination };
32
+ }
33
+ async getCollections() {
34
+ const response = await this.get('/api/v1/collections.json', { params: { page_size: 100 } });
35
+ if (!Array.isArray(response.data?.collections))
36
+ throw new Error('Unexpected response from RideWithGPS collections: expected a list of collections');
37
+ return response.data.collections;
38
+ }
39
+ async getCollection(id) {
40
+ const response = await this.get(`/api/v1/collections/${id}.json`);
41
+ if (!response.data?.collection)
42
+ throw new Error('Unexpected response from RideWithGPS collection: collection is missing');
43
+ return response.data.collection;
44
+ }
45
+ async getRoute(id) {
46
+ const response = await this.get(`/api/v1/routes/${id}.json`);
47
+ if (!response.data?.route)
48
+ throw new Error('Unexpected response from RideWithGPS route: route is missing');
49
+ return response.data.route;
50
+ }
51
+ async getRouteAsGPX(id) {
52
+ const response = await this.get(`/api/v1/routes/${id}.gpx`, { responseType: 'text' });
53
+ if (typeof response.data !== 'string' || response.data.length === 0)
54
+ throw new Error('Unexpected response from RideWithGPS route: no GPX content');
55
+ return response.data;
56
+ }
57
+ async uploadActivity(props) {
58
+ await this.verifyAuthentication();
59
+ const task = await this.createUpload(props);
60
+ const finished = await this.waitForTask(task);
61
+ if (finished.status !== 'completed')
62
+ throw (0, utils_1.getTaskFailure)(finished);
63
+ const result = (0, utils_1.getUploadResult)(finished);
64
+ if (result.tripId && !result.duplicate && props.activityType)
65
+ await this.setActivityType(result.tripId, props.activityType);
66
+ return result;
67
+ }
68
+ async createUpload(props) {
69
+ const fields = { file: { type: 'file', fileName: props.fileName } };
70
+ if (props.name)
71
+ fields.name = props.name;
72
+ if (props.description)
73
+ fields.description = props.description;
74
+ this.logger.logEvent({ message: 'RideWithGPS upload' });
75
+ try {
76
+ const form = await this.createForm('/api/v1/trips.json', fields, { headers: this.getAuthHeaders() });
77
+ const response = await this.postForm(form);
78
+ if (!response.data?.task)
79
+ throw new Error('Unexpected response from RideWithGPS upload: task is missing');
80
+ return response.data.task;
81
+ }
82
+ catch (err) {
83
+ await this.checkRevoked(err);
84
+ throw this.toUploadError(err);
85
+ }
86
+ }
87
+ toUploadError(err) {
88
+ const mapped = this.mapUploadRejection(err);
89
+ return err?.response?.status === 401 ? new types_1.RideWithGpsAuthError(mapped.message) : mapped;
90
+ }
91
+ async getTask(id) {
92
+ const response = await this.request('get', `/api/v1/tasks/${id}.json`, undefined, undefined, { checkRevoked: false });
93
+ if (!response.data?.task)
94
+ throw new Error('Unexpected response from RideWithGPS task: task is missing');
95
+ return response.data.task;
96
+ }
97
+ async waitForTask(initial) {
98
+ let task = initial;
99
+ for (let polls = 0; polls < MAX_POLLS; polls++) {
100
+ if (task.status !== 'pending')
101
+ return task;
102
+ await (0, sleep_1.sleep)(POLL_INTERVAL_MS);
103
+ task = await this.pollTask(task.id);
104
+ }
105
+ if (task.status === 'pending')
106
+ throw new types_1.RideWithGpsTimeoutError();
107
+ return task;
108
+ }
109
+ async pollTask(id) {
110
+ try {
111
+ return await this.getTask(id);
112
+ }
113
+ catch (err) {
114
+ throw new types_1.RideWithGpsTimeoutError('Could not read the status of the RideWithGPS upload: ' + err.message);
115
+ }
116
+ }
117
+ async setActivityType(tripId, activityType) {
118
+ try {
119
+ await this.request('put', `/api/v1/trips/${tripId}.json`, { trip: { activity_type: activityType } }, undefined, { checkRevoked: false });
120
+ }
121
+ catch (err) {
122
+ this.logger.logEvent({ message: 'RideWithGPS set activity type failed', tripId, activityType, error: err.message });
123
+ }
124
+ }
125
+ getExpiration() {
126
+ return new Date(8.64e15);
127
+ }
128
+ }
129
+ exports.RideWithGpsApi = RideWithGpsApi;
@@ -0,0 +1,19 @@
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);
19
+ __exportStar(require("./utils"), exports);
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RideWithGpsAuthError = exports.RideWithGpsTimeoutError = exports.RideWithGpsTimeDataMissingError = void 0;
4
+ class RideWithGpsTimeDataMissingError extends Error {
5
+ constructor(message) {
6
+ super(message ?? 'Upload rejected by RideWithGPS: the file has no time data');
7
+ }
8
+ }
9
+ exports.RideWithGpsTimeDataMissingError = RideWithGpsTimeDataMissingError;
10
+ class RideWithGpsTimeoutError extends Error {
11
+ constructor(message) {
12
+ super(message ?? 'RideWithGPS did not finish processing the upload in time');
13
+ }
14
+ }
15
+ exports.RideWithGpsTimeoutError = RideWithGpsTimeoutError;
16
+ class RideWithGpsAuthError extends Error {
17
+ }
18
+ exports.RideWithGpsAuthError = RideWithGpsAuthError;