incyclist-services 1.9.15 → 1.9.16

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.
package/README.MD CHANGED
@@ -1,29 +1,131 @@
1
1
  # incyclist-services
2
2
 
3
- This Library contains the business logic used by the React components of the [Incyclist](https://incyclist.com) Indoor Cycling App.
3
+ This repository contains the business logic of the [Incyclist](https://incyclist.com)
4
+ indoor cycling app, published on npm as
5
+ [`incyclist-services`](https://www.npmjs.com/package/incyclist-services).
4
6
 
5
- Incyclist uses React to render the App Front-End for PC platforms ( Windows, Mac. Linux). It is planned that in the future, React Native will be used to render the Front-Ends for other platforms ( Android, IOS, AppleTV,...)
7
+ Incyclist separates its user interfaces from its business logic. The front-ends,
8
+ [`web-ui`](https://github.com/incyclist/web-ui) (React, used by the desktop app) and the
9
+ mobile app (React Native), decide *how* things are rendered. This library decides *what* is
10
+ rendered: device pairing, rides, workouts, routes, activities, settings, third-party app
11
+ connections, and so on. A front-end should not contain business logic. If you're changing
12
+ behaviour, this is usually the right repo.
6
13
 
7
- All Services will be accessed by the Front-End using
14
+ ```
15
+ incyclist-devices ──► incyclist-services ──► web-ui ──► desktop app (Electron)
16
+ (trainers, sensors) (this repo) └─► mobile app (React Native)
17
+ ```
18
+
19
+ ## Getting started
20
+
21
+ **Prerequisites:** Node.js 24 or newer (CI tests against 24.x and 25.x) and npm.
22
+
23
+ ```bash
24
+ git clone https://github.com/incyclist/services.git
25
+ cd services
26
+ npm install
27
+ npm run build
28
+ npm test
29
+ ```
30
+
31
+ If the build and the unit tests pass, you're set up. You don't need any devices, accounts or
32
+ credentials to work on this repo: unit tests mock everything external.
33
+
34
+ ## Available scripts
35
+
36
+ | Script | Purpose |
37
+ |---|---|
38
+ | `npm run build` | Build ESM (`lib/esm`) and CJS (`lib/cjs`) output |
39
+ | `npm run dev` | Watch mode: rebuilds `lib/esm` on every change (see below) |
40
+ | `npm test` | Run the unit tests. Scope to a file or folder with `npm test -- <path>` |
41
+ | `npm run coverage` | Unit tests with a coverage report |
42
+ | `npm run lint` | ESLint |
43
+ | `npm run typecheck` | TypeScript type check (`tsc --noEmit`), including test files |
44
+ | `npm run test:e2e` | E2E tests against real backends. Maintainers only, see below |
45
+
46
+ Don't run bare `npx jest` or `npm run test:all`: both include the E2E tests.
47
+
48
+ ### About E2E tests
49
+
50
+ Files named `*.e2e.test.ts` talk to real services (Incyclist backend, Strava, Komoot,
51
+ intervals.icu, VeloHero, ...). They need credentials in a local `.env` file and can create or
52
+ change real data. Contributors don't need them. CI runs the unit tests, lint and type check
53
+ only.
8
54
 
55
+ ## Working on services together with a front-end
56
+
57
+ To see your changes in the running app, clone [`web-ui`](https://github.com/incyclist/web-ui)
58
+ and [`devices`](https://github.com/incyclist/devices) next to this repo:
59
+
60
+ ```
61
+ <your-folder>
62
+ ├── services (this repo)
63
+ ├── devices
64
+ └── web-ui
9
65
  ```
10
- import {useXXX, initXXX} from {incyclist-devices}
11
66
 
67
+ In dev mode, `web-ui` loads both `incyclist-services` and `incyclist-devices` from these
68
+ sibling folders (`../services/lib/esm`, `../devices/lib/esm`) instead of `node_modules`. So:
69
+
70
+ 1. Run `npm install` and `npm run build` once in `devices` and in `services`.
71
+ `lib/esm` must exist in both.
72
+ 2. Run `npm run dev` here. It rebuilds on every change.
73
+ 3. Run `npm run dev` in `web-ui`. Every change you save here now shows up in the UI.
74
+
75
+ See the [web-ui README](https://github.com/incyclist/web-ui#readme) for how to point the
76
+ desktop app at your local UI.
77
+
78
+ ## Project structure
79
+
80
+ Each folder under `src/` is a domain module with its own `index.ts`, `types.ts`, service
81
+ classes and colocated `*.unit.test.ts` files.
82
+
83
+ | Module | What it covers |
84
+ |---|---|
85
+ | `activities` | Recording, saving, listing and uploading completed rides |
86
+ | `api` | Platform bindings (file system, settings, BLE/ANT+/serial, MQTT, ...) and REST helpers |
87
+ | `apps` | Connected third-party apps: Strava, intervals.icu, Komoot, ... |
88
+ | `appstate` | App state and feature toggles |
89
+ | `autoupdate` | UI bundle update checks |
90
+ | `avatars` | Rider avatars |
91
+ | `base` | Base classes and decorators shared by all services |
92
+ | `coaches` | Virtual riders to ride against |
93
+ | `devices` | Device configuration, access, pairing and in-ride device handling |
94
+ | `fileaccess` | Loading local and external files |
95
+ | `i18n` | Localization, countries, units |
96
+ | `maps`, `services` | Map areas and OpenStreetMap (Overpass) queries |
97
+ | `monitoring` | Online/offline status |
98
+ | `ride` | The live ride: display, controls, route/workout/video ride modes |
99
+ | `routes` | Route list, parsing, download and import |
100
+ | `settings` | User settings |
101
+ | `ui` | UI-facing helpers |
102
+ | `video` | Video handling for video routes |
103
+ | `workouts` | Workout list, import, parsing and execution |
104
+
105
+ Everything consumers may use is exported from `src/index.ts`:
106
+
107
+ ```ts
108
+ import { useDeviceConfiguration, initUserSettings } from 'incyclist-services'
12
109
  ```
13
110
 
14
- - useXXX can be used to consume a Service (e.g. `useDeviceConfiguration()` )
15
- - initXXX can be used to perform a lazy initialization of the Service (e.g. `initUserSettings(binding)` )
111
+ `useXXX()` returns a service singleton, and `initXXX()` initializes one where needed.
112
+
113
+ ## Using this library in your own app
114
+
115
+ The library never calls platform APIs directly. File access, settings storage, secrets,
116
+ Bluetooth, ANT+ and so on all go through bindings (`src/api/bindings/`) that the host app
117
+ must provide at startup. A fork or a new front-end has to supply its own implementations.
118
+ The existing front-ends (`web-ui` for browser/Electron, the mobile app for React Native)
119
+ are the reference for how this is done.
16
120
 
17
- where XXX represents the Service name
121
+ ## Contributing
18
122
 
19
- The following Services are currently implemented in this library:
123
+ Contributions are welcome. Please read:
20
124
 
21
- ## Settings
22
- - [UserSettings](./doc/classes/UserSettingsService.md): manages the user settings
125
+ - [CONTRIBUTING.md](./CONTRIBUTING.md): workflow, branches, pull requests
126
+ - [docs/CODEBASE_GUIDE.md](./docs/CODEBASE_GUIDE.md): architecture, coding style and testing
127
+ conventions. Please read this before writing code.
23
128
 
129
+ ## License
24
130
 
25
- ## Devices
26
- - [DeviceConfiguration](./doc/classes/DeviceConfigurationService.md): manages the user configuration of scanned/added/selected devices
27
- - [DeviceAccess](./doc/classes/DeviceAccessService.md): manages the basic communication to the device (setting up interfacs, scanning,... )
28
- - [Device](./src/devices/device/README.MD): allows the Front-End to communicate with a device (reading, writing data)
29
- - [DevicePairing](./doc/classes/DevicePairingService.md): implements the business logic og the DevicePairing screens
131
+ [MIT](./LICENSE)
@@ -167,8 +167,34 @@ let RouteCard = (() => {
167
167
  const descr = this.getRouteDescription();
168
168
  if (!descr?.hasVideo || descr?.videoUrl === undefined)
169
169
  return false;
170
- const videoUrl = descr.videoUrl;
171
- if (!descr.videoUrl)
170
+ return this.urlExists(descr.videoUrl);
171
+ }
172
+ async recoverDownloadState() {
173
+ const descr = this.getRouteDescription();
174
+ const localUrl = this.getRouteData()?.video?.url;
175
+ if (!descr?.hasVideo || descr.isLocal || descr.isDownloaded)
176
+ return false;
177
+ if (!localUrl || !(localUrl.startsWith('video:///') || localUrl.startsWith('file:///')))
178
+ return false;
179
+ const remote = [descr.downloadUrl, descr.originalVideoUrl, descr.videoUrl].find(u => u?.startsWith('http'));
180
+ if (!remote || this.fileNameOf(remote) !== this.fileNameOf(localUrl))
181
+ return false;
182
+ if (!(await this.urlExists(localUrl)))
183
+ return false;
184
+ descr.originalVideoUrl ??= remote;
185
+ descr.downloadUrl ??= remote;
186
+ descr.videoUrl = localUrl;
187
+ descr.isDownloaded = true;
188
+ await this.save();
189
+ this.emitUpdate();
190
+ return true;
191
+ }
192
+ fileNameOf(url) {
193
+ const name = url.split('?')[0].split(/[\\/]/).pop() ?? '';
194
+ return this.cleanupEncoding(name);
195
+ }
196
+ async urlExists(videoUrl) {
197
+ if (!videoUrl)
172
198
  return true;
173
199
  const normalizedUrl = videoUrl.replace('video:////', 'video:///').replace('file:////', 'file:///');
174
200
  let path = undefined;
@@ -161,10 +161,11 @@ let RoutesDbLoader = (() => {
161
161
  await this.saveObserver.wait();
162
162
  const save = async () => {
163
163
  try {
164
- await this.routesRepo.write('db', this.routeDescriptions.map(this.buildRouteDBInfo.bind(this)));
165
164
  this.isDirty = false;
165
+ await this.routesRepo.write('db', this.routeDescriptions.map(this.buildRouteDBInfo.bind(this)));
166
166
  }
167
167
  catch (err) {
168
+ this.isDirty = true;
168
169
  this.logger.logEvent({ message: 'could not safe repo', error: err.message });
169
170
  }
170
171
  };
@@ -1172,6 +1172,28 @@ let RouteListService = (() => {
1172
1172
  }).catch(err => { this.logError(err, 'loadRoutes'); });
1173
1173
  this.startSync();
1174
1174
  }
1175
+ async recoverDownloadStates(cards) {
1176
+ const candidates = cards.filter(card => {
1177
+ const descr = card?.getRouteDescription();
1178
+ return descr?.hasVideo && !descr.isLocal && !descr.isDownloaded && descr.originalVideoUrl;
1179
+ });
1180
+ await Promise.allSettled(candidates.map(card => this.recoverDownloadState(card)));
1181
+ }
1182
+ async recoverDownloadState(card) {
1183
+ try {
1184
+ if (!card.getRouteData()) {
1185
+ const details = await this.db.getDetails(card.getId());
1186
+ if (!details)
1187
+ return;
1188
+ card.setRouteData(details);
1189
+ }
1190
+ if (await card.recoverDownloadState())
1191
+ this.logEvent({ message: 'preload route updated', route: card.getRouteDescription().title, reason: 'download state recovered' });
1192
+ }
1193
+ catch (err) {
1194
+ this.logError(err, 'recoverDownloadState');
1195
+ }
1196
+ }
1175
1197
  async preloadDetails() {
1176
1198
  const { cards = [] } = this.searchRepo();
1177
1199
  const promises = [];
@@ -1216,6 +1238,7 @@ let RouteListService = (() => {
1216
1238
  }
1217
1239
  });
1218
1240
  await Promise.allSettled(promises);
1241
+ await this.recoverDownloadStates(cards);
1219
1242
  }
1220
1243
  startSync() {
1221
1244
  try {
@@ -164,8 +164,34 @@ let RouteCard = (() => {
164
164
  const descr = this.getRouteDescription();
165
165
  if (!descr?.hasVideo || descr?.videoUrl === undefined)
166
166
  return false;
167
- const videoUrl = descr.videoUrl;
168
- if (!descr.videoUrl)
167
+ return this.urlExists(descr.videoUrl);
168
+ }
169
+ async recoverDownloadState() {
170
+ const descr = this.getRouteDescription();
171
+ const localUrl = this.getRouteData()?.video?.url;
172
+ if (!descr?.hasVideo || descr.isLocal || descr.isDownloaded)
173
+ return false;
174
+ if (!localUrl || !(localUrl.startsWith('video:///') || localUrl.startsWith('file:///')))
175
+ return false;
176
+ const remote = [descr.downloadUrl, descr.originalVideoUrl, descr.videoUrl].find(u => u?.startsWith('http'));
177
+ if (!remote || this.fileNameOf(remote) !== this.fileNameOf(localUrl))
178
+ return false;
179
+ if (!(await this.urlExists(localUrl)))
180
+ return false;
181
+ descr.originalVideoUrl ??= remote;
182
+ descr.downloadUrl ??= remote;
183
+ descr.videoUrl = localUrl;
184
+ descr.isDownloaded = true;
185
+ await this.save();
186
+ this.emitUpdate();
187
+ return true;
188
+ }
189
+ fileNameOf(url) {
190
+ const name = url.split('?')[0].split(/[\\/]/).pop() ?? '';
191
+ return this.cleanupEncoding(name);
192
+ }
193
+ async urlExists(videoUrl) {
194
+ if (!videoUrl)
169
195
  return true;
170
196
  const normalizedUrl = videoUrl.replace('video:////', 'video:///').replace('file:////', 'file:///');
171
197
  let path = undefined;
@@ -155,10 +155,11 @@ let RoutesDbLoader = (() => {
155
155
  await this.saveObserver.wait();
156
156
  const save = async () => {
157
157
  try {
158
- await this.routesRepo.write('db', this.routeDescriptions.map(this.buildRouteDBInfo.bind(this)));
159
158
  this.isDirty = false;
159
+ await this.routesRepo.write('db', this.routeDescriptions.map(this.buildRouteDBInfo.bind(this)));
160
160
  }
161
161
  catch (err) {
162
+ this.isDirty = true;
162
163
  this.logger.logEvent({ message: 'could not safe repo', error: err.message });
163
164
  }
164
165
  };
@@ -1166,6 +1166,28 @@ let RouteListService = (() => {
1166
1166
  }).catch(err => { this.logError(err, 'loadRoutes'); });
1167
1167
  this.startSync();
1168
1168
  }
1169
+ async recoverDownloadStates(cards) {
1170
+ const candidates = cards.filter(card => {
1171
+ const descr = card?.getRouteDescription();
1172
+ return descr?.hasVideo && !descr.isLocal && !descr.isDownloaded && descr.originalVideoUrl;
1173
+ });
1174
+ await Promise.allSettled(candidates.map(card => this.recoverDownloadState(card)));
1175
+ }
1176
+ async recoverDownloadState(card) {
1177
+ try {
1178
+ if (!card.getRouteData()) {
1179
+ const details = await this.db.getDetails(card.getId());
1180
+ if (!details)
1181
+ return;
1182
+ card.setRouteData(details);
1183
+ }
1184
+ if (await card.recoverDownloadState())
1185
+ this.logEvent({ message: 'preload route updated', route: card.getRouteDescription().title, reason: 'download state recovered' });
1186
+ }
1187
+ catch (err) {
1188
+ this.logError(err, 'recoverDownloadState');
1189
+ }
1190
+ }
1169
1191
  async preloadDetails() {
1170
1192
  const { cards = [] } = this.searchRepo();
1171
1193
  const promises = [];
@@ -1210,6 +1232,7 @@ let RouteListService = (() => {
1210
1232
  }
1211
1233
  });
1212
1234
  await Promise.allSettled(promises);
1235
+ await this.recoverDownloadStates(cards);
1213
1236
  }
1214
1237
  startSync() {
1215
1238
  try {
@@ -52,6 +52,9 @@ export declare class RouteCard extends BaseCard implements Card<Route> {
52
52
  verify(): void;
53
53
  protected isVideoMissing(): Promise<boolean>;
54
54
  videoExists(): Promise<boolean>;
55
+ recoverDownloadState(): Promise<boolean>;
56
+ protected fileNameOf(url: string): string;
57
+ protected urlExists(videoUrl: string | undefined): Promise<boolean>;
55
58
  protected fileExists(path: string): Promise<boolean>;
56
59
  cleanupEncoding(path: string): string;
57
60
  previewMissing(): boolean;
@@ -178,6 +178,8 @@ export declare class RouteListService extends IncyclistService implements IRoute
178
178
  protected addFromApi(route: Route): Promise<void>;
179
179
  protected update(route: Route, _source?: 'user' | 'system'): Promise<void>;
180
180
  protected loadRoutes(): Promise<void>;
181
+ protected recoverDownloadStates(cards: Array<RouteCard>): Promise<void>;
182
+ protected recoverDownloadState(card: RouteCard): Promise<void>;
181
183
  protected preloadDetails(): Promise<void>;
182
184
  protected startSync(): void;
183
185
  protected getSyncFrequency(): any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incyclist-services",
3
- "version": "1.9.15",
3
+ "version": "1.9.16",
4
4
  "peerDependencies": {
5
5
  "gd-eventlog": "^0.1.27"
6
6
  },
@@ -11,7 +11,7 @@
11
11
  "promise.any": "^2.0.6",
12
12
  "semver": "^7.7.4",
13
13
  "tcx-builder": "^1.1.1",
14
- "uuid": "^14.0.2",
14
+ "uuid": "^14.0.3",
15
15
  "xml2js": "^0.6.2"
16
16
  },
17
17
  "devDependencies": {
@@ -23,14 +23,14 @@
23
23
  "@typescript-eslint/eslint-plugin": "^8.72.1",
24
24
  "@typescript-eslint/parser": "^8.71.0",
25
25
  "dotenv": "^17.4.2",
26
- "eslint": "^10.12.0",
26
+ "eslint": "^10.13.0",
27
27
  "formdata-node": "^6.0.3",
28
28
  "globals": "^17.13.0",
29
29
  "jest": "^30.5.2",
30
30
  "jsdoc": "^4.0.5",
31
31
  "ts-jest": "^29.4.12",
32
32
  "typedoc": "^0.28.20",
33
- "typedoc-plugin-markdown": "^4.13.1",
33
+ "typedoc-plugin-markdown": "^4.14.1",
34
34
  "typedoc-plugin-no-inherit": "^1.6.1",
35
35
  "typescript": "^5.9.3",
36
36
  "typescript-eslint": "^8.67.0"