incyclist-services 1.9.31 → 1.9.32

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 (77) hide show
  1. package/lib/cjs/activities/upload/index.js +1 -0
  2. package/lib/cjs/activities/upload/komoot.js +2 -2
  3. package/lib/cjs/activities/upload/ridewithgps.js +158 -0
  4. package/lib/cjs/apps/base/api/index.js +1 -0
  5. package/lib/cjs/apps/base/api/oauth.js +45 -5
  6. package/lib/cjs/apps/base/api/ridewithgps/api.js +129 -0
  7. package/lib/cjs/apps/base/api/ridewithgps/index.js +19 -0
  8. package/lib/cjs/apps/base/api/ridewithgps/types.js +18 -0
  9. package/lib/cjs/apps/base/api/ridewithgps/utils.js +42 -0
  10. package/lib/cjs/apps/base/app/OAuthAppConnection.js +21 -4
  11. package/lib/cjs/apps/index.js +1 -0
  12. package/lib/cjs/apps/ridewithgps/RideWithGpsAppConnection.js +83 -0
  13. package/lib/cjs/apps/ridewithgps/index.js +18 -0
  14. package/lib/cjs/apps/ridewithgps/types.js +2 -0
  15. package/lib/cjs/apps/service.js +11 -1
  16. package/lib/cjs/coaches/coach.js +14 -6
  17. package/lib/cjs/devices/ride/service.js +42 -0
  18. package/lib/cjs/ride/base/base.js +14 -0
  19. package/lib/cjs/ride/route/RLVDisplayService.js +18 -4
  20. package/lib/cjs/routes/sync/base/provider.js +51 -9
  21. package/lib/cjs/routes/sync/index.js +1 -0
  22. package/lib/cjs/routes/sync/komoot/provider.js +1 -27
  23. package/lib/cjs/routes/sync/ridewithgps/provider.js +182 -0
  24. package/lib/cjs/routes/sync/strava/provider.js +1 -28
  25. package/lib/cjs/video/VideoConversion.js +3 -0
  26. package/lib/esm/activities/upload/index.js +1 -0
  27. package/lib/esm/activities/upload/komoot.js +2 -2
  28. package/lib/esm/activities/upload/ridewithgps.js +155 -0
  29. package/lib/esm/apps/base/api/index.js +1 -0
  30. package/lib/esm/apps/base/api/oauth.js +45 -5
  31. package/lib/esm/apps/base/api/ridewithgps/api.js +125 -0
  32. package/lib/esm/apps/base/api/ridewithgps/index.js +3 -0
  33. package/lib/esm/apps/base/api/ridewithgps/types.js +12 -0
  34. package/lib/esm/apps/base/api/ridewithgps/utils.js +34 -0
  35. package/lib/esm/apps/base/app/OAuthAppConnection.js +21 -4
  36. package/lib/esm/apps/index.js +1 -0
  37. package/lib/esm/apps/ridewithgps/RideWithGpsAppConnection.js +80 -0
  38. package/lib/esm/apps/ridewithgps/index.js +2 -0
  39. package/lib/esm/apps/ridewithgps/types.js +1 -0
  40. package/lib/esm/apps/service.js +11 -1
  41. package/lib/esm/coaches/coach.js +14 -6
  42. package/lib/esm/devices/ride/service.js +42 -0
  43. package/lib/esm/ride/base/base.js +14 -0
  44. package/lib/esm/ride/route/RLVDisplayService.js +18 -4
  45. package/lib/esm/routes/sync/base/provider.js +51 -9
  46. package/lib/esm/routes/sync/index.js +1 -0
  47. package/lib/esm/routes/sync/komoot/provider.js +1 -27
  48. package/lib/esm/routes/sync/ridewithgps/provider.js +178 -0
  49. package/lib/esm/routes/sync/strava/provider.js +1 -28
  50. package/lib/esm/video/VideoConversion.js +3 -0
  51. package/lib/types/activities/upload/index.d.ts +1 -0
  52. package/lib/types/activities/upload/ridewithgps.d.ts +30 -0
  53. package/lib/types/apps/base/api/index.d.ts +1 -0
  54. package/lib/types/apps/base/api/oauth.d.ts +7 -1
  55. package/lib/types/apps/base/api/ridewithgps/api.d.ts +18 -0
  56. package/lib/types/apps/base/api/ridewithgps/index.d.ts +3 -0
  57. package/lib/types/apps/base/api/ridewithgps/types.d.ts +104 -0
  58. package/lib/types/apps/base/api/ridewithgps/utils.d.ts +9 -0
  59. package/lib/types/apps/base/api/types.d.ts +3 -2
  60. package/lib/types/apps/base/app/OAuthAppConnection.d.ts +6 -1
  61. package/lib/types/apps/base/types.d.ts +1 -1
  62. package/lib/types/apps/index.d.ts +1 -0
  63. package/lib/types/apps/ridewithgps/RideWithGpsAppConnection.d.ts +13 -0
  64. package/lib/types/apps/ridewithgps/index.d.ts +2 -0
  65. package/lib/types/apps/ridewithgps/types.d.ts +2 -0
  66. package/lib/types/apps/service.d.ts +1 -0
  67. package/lib/types/apps/types.d.ts +1 -0
  68. package/lib/types/coaches/coach.d.ts +1 -0
  69. package/lib/types/devices/ride/service.d.ts +5 -1
  70. package/lib/types/ride/base/base.d.ts +1 -0
  71. package/lib/types/ride/base/types.d.ts +7 -0
  72. package/lib/types/ride/route/RLVDisplayService.d.ts +3 -2
  73. package/lib/types/routes/sync/base/provider.d.ts +5 -1
  74. package/lib/types/routes/sync/index.d.ts +1 -0
  75. package/lib/types/routes/sync/ridewithgps/provider.d.ts +41 -0
  76. package/lib/types/video/VideoConversion.d.ts +1 -0
  77. package/package.json +2 -2
@@ -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());
@@ -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;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getUploadResult = exports.getTaskFailure = exports.isOwnActiveRoute = exports.isSyncedCollection = exports.isRoadCyclingRoute = exports.UNPAVED_THRESHOLD_PCT = void 0;
4
+ const types_1 = require("./types");
5
+ exports.UNPAVED_THRESHOLD_PCT = 50;
6
+ const OFFROAD_TYPES = new Set(['cycling:gravel', 'cycling:mountain', 'cycling:cyclocross']);
7
+ const OTHER_SPORTS = ['walking:', 'running:', 'driving:', 'motorcycling:', 'swimming:', 'snow:'];
8
+ const isClearlyNotRoad = (type) => OFFROAD_TYPES.has(type) || OTHER_SPORTS.some(sport => type.startsWith(sport));
9
+ const isRoadCyclingRoute = (route) => {
10
+ const types = route.activity_types;
11
+ if (Array.isArray(types) && types.length > 0)
12
+ return !types.every(isClearlyNotRoad);
13
+ return !(typeof route.unpaved_pct === 'number' && route.unpaved_pct >= exports.UNPAVED_THRESHOLD_PCT);
14
+ };
15
+ exports.isRoadCyclingRoute = isRoadCyclingRoute;
16
+ const SYNCED_COLLECTIONS = new Set(['pinned', 'bucket list']);
17
+ const isSyncedCollection = (collection) => {
18
+ const name = (collection.name ?? '').toLowerCase().replaceAll(/[{}_]/g, ' ').trim().replaceAll(/\s+/g, ' ');
19
+ return SYNCED_COLLECTIONS.has(name);
20
+ };
21
+ exports.isSyncedCollection = isSyncedCollection;
22
+ const isOwnActiveRoute = (route) => route.archived !== true && route.archived !== null;
23
+ exports.isOwnActiveRoute = isOwnActiveRoute;
24
+ const describeError = (error) => `Upload rejected by RideWithGPS: ${error.code}${error.message ? ' (' + error.message + ')' : ''}`;
25
+ const getTaskFailure = (task) => task.errors?.length ? new Error(describeError(task.errors[0])) : new Error(`RideWithGPS upload ended with status ${task.status}`);
26
+ exports.getTaskFailure = getTaskFailure;
27
+ const getUploadResult = (task) => {
28
+ const created = task.items?.find(item => item.item_type === 'trip') ?? task.items?.[0];
29
+ if (created)
30
+ return { tripId: String(created.item_id) };
31
+ const errors = task.errors ?? [];
32
+ const duplicate = errors.find(e => e.code === 'duplicate');
33
+ if (duplicate) {
34
+ const tripId = duplicate.item_id === undefined || duplicate.item_id === null ? undefined : String(duplicate.item_id);
35
+ return { tripId, duplicate: true };
36
+ }
37
+ const timeMissing = errors.find(e => e.code === 'time_data_missing');
38
+ if (timeMissing)
39
+ throw new types_1.RideWithGpsTimeDataMissingError(describeError(timeMissing));
40
+ throw new Error(errors.length > 0 ? describeError(errors[0]) : 'RideWithGPS did not create a trip');
41
+ };
42
+ exports.getUploadResult = getUploadResult;
@@ -9,6 +9,10 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
9
9
  this.logEvent({ message: `Connect with ${this.appName}` });
10
10
  try {
11
11
  const config = this.createConfig(credentials);
12
+ if (!(0, valid_1.valid)(config?.accessToken)) {
13
+ this.logEvent({ message: `Connect with ${this.appName} failed`, reason: 'no access token' });
14
+ return false;
15
+ }
12
16
  if (this.isConnected()) {
13
17
  this.getApi().update(config);
14
18
  }
@@ -41,7 +45,7 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
41
45
  if (!this.isInitialized) {
42
46
  this.init();
43
47
  }
44
- return (0, valid_1.valid)(this.config);
48
+ return (0, valid_1.valid)(this.config) && (0, valid_1.valid)(this.config.accessToken);
45
49
  }
46
50
  getCredentials() {
47
51
  try {
@@ -63,8 +67,9 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
63
67
  try {
64
68
  const auth = this.getCredentials();
65
69
  this.logEvent({ message: `${this.appName} init done`, hasCredentials: Boolean(auth) });
66
- if (auth) {
67
- this.config = this.createConfig(auth);
70
+ const config = auth ? this.createConfig(auth) : undefined;
71
+ if ((0, valid_1.valid)(config?.accessToken)) {
72
+ this.config = config;
68
73
  this.initApi(this.config);
69
74
  }
70
75
  return true;
@@ -100,7 +105,19 @@ class OAuthAppConnection extends ConnectedAppService_1.ConnectedAppService {
100
105
  }
101
106
  initApi(config) {
102
107
  const observer = this.getApi().init(config);
103
- observer.on('token.updated', (updated) => { this.updateConfig(updated); });
108
+ if (this.apiListeners) {
109
+ this.apiListeners.observer.off('token.updated', this.apiListeners.onToken);
110
+ this.apiListeners.observer.off('auth.failed', this.apiListeners.onFailed);
111
+ }
112
+ const onToken = (updated) => { this.updateConfig(updated); };
113
+ const onFailed = () => {
114
+ this.logEvent({ message: `${this.appName} authentication failed, credentials removed (reconnect required)` });
115
+ this.disconnect();
116
+ this.emit('auth.failed');
117
+ };
118
+ observer.on('token.updated', onToken);
119
+ observer.on('auth.failed', onFailed);
120
+ this.apiListeners = { observer, onToken, onFailed };
104
121
  }
105
122
  }
106
123
  exports.OAuthAppConnection = OAuthAppConnection;
@@ -20,3 +20,4 @@ __exportStar(require("./service"), exports);
20
20
  __exportStar(require("./strava"), exports);
21
21
  __exportStar(require("./trainingpeaks"), exports);
22
22
  __exportStar(require("./trainerday"), exports);
23
+ __exportStar(require("./ridewithgps"), exports);
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.RideWithGpsAppConnection = void 0;
38
+ const decorators_1 = require("../../base/decorators");
39
+ const api_1 = require("../base/api");
40
+ const app_1 = require("../base/app");
41
+ let RideWithGpsAppConnection = (() => {
42
+ let _classDecorators = [decorators_1.Singleton];
43
+ let _classDescriptor;
44
+ let _classExtraInitializers = [];
45
+ let _classThis;
46
+ let _classSuper = app_1.OAuthAppConnection;
47
+ var RideWithGpsAppConnection = class extends _classSuper {
48
+ static { _classThis = this; }
49
+ static {
50
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
51
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
52
+ RideWithGpsAppConnection = _classThis = _classDescriptor.value;
53
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
54
+ __runInitializers(_classThis, _classExtraInitializers);
55
+ }
56
+ constructor() {
57
+ super('RideWithGpsAppConnection', 'ridewithgps');
58
+ }
59
+ getSupportedOperations() {
60
+ return ['ActivityUpload', 'RouteDownload'];
61
+ }
62
+ getDefaultOperations() {
63
+ return ['ActivityUpload', 'RouteDownload'];
64
+ }
65
+ get appName() {
66
+ return 'RideWithGPS';
67
+ }
68
+ createApi() {
69
+ return new api_1.RideWithGpsApi();
70
+ }
71
+ createConfig(credentials) {
72
+ return {
73
+ id: credentials?.id === undefined || credentials.id === null ? undefined : String(credentials.id),
74
+ accessToken: credentials?.accesstoken
75
+ };
76
+ }
77
+ createCredentials(config) {
78
+ return { id: config.id, accesstoken: config.accessToken };
79
+ }
80
+ };
81
+ return RideWithGpsAppConnection = _classThis;
82
+ })();
83
+ exports.RideWithGpsAppConnection = RideWithGpsAppConnection;
@@ -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("./RideWithGpsAppConnection"), exports);
18
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });