1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
|
/* eslint-disable import/no-import-module-exports */
/* eslint-disable global-require */
import { join } from 'node:path';
import tar from 'tar';
import {
readdirSync,
statSync,
writeFileSync,
copySync,
ensureDirSync,
pathExistsSync,
readJsonSync,
removeSync,
PathOrFileDescriptor,
} from 'fs-extra';
import ServiceModel from '../../models/Service';
import RecipePreviewModel, { IRecipePreview } from '../../models/RecipePreview';
import RecipeModel, { IRecipe } from '../../models/Recipe';
import UserModel from '../../models/User';
import sleep from '../../helpers/async-helpers';
import { SERVER_NOT_LOADED } from '../../config';
import { userDataRecipesPath, userDataPath } from '../../environment-remote';
import { asarRecipesPath } from '../../helpers/asar-helpers';
import apiBase from '../apiBase';
import {
prepareAuthRequest,
prepareLocalToken,
sendAuthRequest,
} from '../utils/auth';
import {
getRecipeDirectory,
getDevRecipeDirectory,
loadRecipeConfig,
} from '../../helpers/recipe-helpers';
import { removeServicePartitionDirectory } from '../../helpers/service-helpers';
const debug = require('../../preload-safe-debug')('Ferdium:ServerApi');
module.paths.unshift(getDevRecipeDirectory(), getRecipeDirectory());
export default class ServerApi {
recipePreviews: IRecipePreview[] = [];
recipes: IRecipe[] = [];
// User
async login(email: string, passwordHash: string) {
const request = await sendAuthRequest(
`${apiBase()}/auth/login`,
{
method: 'POST',
headers: {
Authorization: `Basic ${Buffer.from(
`${email}:${passwordHash}`,
).toString('base64')}`,
},
},
false,
);
try {
const responseJson = await request.json();
if (!request.ok) {
throw responseJson;
}
debug('ServerApi::login resolves', responseJson);
return responseJson.token;
} catch (error) {
debug('ServerApi::login ERROR:', error);
throw error;
}
}
async signup(data: any) {
const request = await sendAuthRequest(
`${apiBase()}/auth/signup`,
{
method: 'POST',
body: JSON.stringify(data),
},
false,
);
try {
const responseJson = await request.json();
if (!request.ok) {
throw responseJson;
}
debug('ServerApi::signup resolves', responseJson);
return responseJson.token;
} catch (error) {
debug('ServerApi::signup ERROR:', error);
throw error;
}
}
async inviteUser(data: any) {
const request = await sendAuthRequest(`${apiBase()}/invite`, {
method: 'POST',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
debug('ServerApi::inviteUser');
return true;
}
async retrievePassword(email: string) {
const request = await sendAuthRequest(
`${apiBase()}/auth/password`,
{
method: 'POST',
body: JSON.stringify({
email,
}),
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const r = await request.json();
debug('ServerApi::retrievePassword');
return r;
}
async userInfo() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/me`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const user = new UserModel(data);
debug('ServerApi::userInfo resolves', user);
return user;
}
async updateUserInfo(data: any) {
const request = await sendAuthRequest(`${apiBase()}/me`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const updatedData = await request.json();
const user = Object.assign(updatedData, {
data: new UserModel(updatedData.data),
});
debug('ServerApi::updateUserInfo resolves', user);
return user;
}
async deleteAccount() {
const request = await sendAuthRequest(`${apiBase()}/me`, {
method: 'DELETE',
});
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
debug('ServerApi::deleteAccount resolves', data);
return data;
}
// Services
async getServices() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/me/services`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const services = await this._mapServiceModels(data);
const filteredServices = services.filter(service => !!service);
debug('ServerApi::getServices resolves', filteredServices);
return filteredServices;
}
async createService(recipeId: string, data: { iconFile: any }) {
const request = await sendAuthRequest(`${apiBase()}/service`, {
method: 'POST',
body: JSON.stringify({ recipeId, ...data }),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
if (data.iconFile) {
const iconData = await this.uploadServiceIcon(
serviceData.data.id,
data.iconFile,
);
serviceData.data = iconData;
}
const service = Object.assign(serviceData, {
data: await this._prepareServiceModel(serviceData.data),
});
debug('ServerApi::createService resolves', service);
return service;
}
async updateService(serviceId: string, rawData: any) {
const data = rawData;
if (data.iconFile) {
await this.uploadServiceIcon(serviceId, data.iconFile);
}
const request = await sendAuthRequest(`${apiBase()}/service/${serviceId}`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
const service = Object.assign(serviceData, {
data: await this._prepareServiceModel(serviceData.data),
});
debug('ServerApi::updateService resolves', service);
return service;
}
async uploadServiceIcon(serviceId: string, icon: string | Blob) {
const formData = new FormData();
formData.append('icon', icon);
const requestData = prepareAuthRequest({
method: 'PUT',
// @ts-expect-error Argument of type '{ method: string; body: FormData; }' is not assignable to parameter of type '{ method: string; }'.
body: formData,
});
delete requestData.headers['Content-Type'];
await prepareLocalToken(requestData);
const request = await window.fetch(
`${apiBase()}/service/${serviceId}`,
// @ts-expect-error Argument of type '{ method: string; } & { mode: string; headers: any; }' is not assignable to parameter of type 'RequestInit | undefined'.
requestData,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
return serviceData.data;
}
async reorderService(data: any) {
const request = await sendAuthRequest(`${apiBase()}/service/reorder`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
debug('ServerApi::reorderService resolves', serviceData);
return serviceData;
}
async deleteService(id: string) {
const request = await sendAuthRequest(`${apiBase()}/service/${id}`, {
method: 'DELETE',
});
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
removeServicePartitionDirectory(id, true);
debug('ServerApi::deleteService resolves', data);
return data;
}
// Features
async getDefaultFeatures() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/features/default`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const features = data;
debug('ServerApi::getDefaultFeatures resolves', features);
return features;
}
async getFeatures() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/features`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const features = data;
debug('ServerApi::getFeatures resolves', features);
return features;
}
// Recipes
async getInstalledRecipes() {
const recipesDirectory = getRecipeDirectory();
const paths = readdirSync(recipesDirectory).filter(
file =>
statSync(join(recipesDirectory, file)).isDirectory() &&
file !== 'temp' &&
file !== 'dev',
);
this.recipes = paths
.map(id => {
// eslint-disable-next-line import/no-dynamic-require
const Recipe = require(id)(RecipeModel);
return new Recipe(loadRecipeConfig(id));
})
.filter(recipe => recipe.id);
// @ts-expect-error Type 'boolean' is not assignable to type 'ConcatArray<IRecipe>'.
// eslint-disable-next-line unicorn/prefer-spread
this.recipes = this.recipes.concat(this._getDevRecipes());
debug('StubServerApi::getInstalledRecipes resolves', this.recipes);
return this.recipes;
}
async getRecipeUpdates(recipeVersions: any) {
const request = await sendAuthRequest(`${apiBase()}/recipes/update`, {
method: 'POST',
body: JSON.stringify(recipeVersions),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const recipes = await request.json();
debug('ServerApi::getRecipeUpdates resolves', recipes);
return recipes;
}
// Recipes Previews
async getRecipePreviews() {
const request = await sendAuthRequest(`${apiBase()}/recipes`);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::getRecipes resolves', recipePreviews);
return recipePreviews;
}
async getFeaturedRecipePreviews() {
const request = await sendAuthRequest(`${apiBase()}/recipes/popular`);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
// data = this._addLocalRecipesToPreviews(data);
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::getFeaturedRecipes resolves', recipePreviews);
return recipePreviews;
}
async searchRecipePreviews(needle: string) {
const url = `${apiBase()}/recipes/search?needle=${needle}`;
const request = await sendAuthRequest(url);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::searchRecipePreviews resolves', recipePreviews);
return recipePreviews;
}
async getRecipePackage(recipeId: string) {
const recipesDirectory = userDataRecipesPath();
const recipeTempDirectory = join(recipesDirectory, 'temp', recipeId);
const tempArchivePath = join(recipeTempDirectory, 'recipe.tar.gz');
const internalRecipeFile = asarRecipesPath(`${recipeId}.tar.gz`);
ensureDirSync(recipeTempDirectory);
let archivePath: PathOrFileDescriptor;
if (pathExistsSync(internalRecipeFile)) {
debug('[ServerApi::getRecipePackage] Using internal recipe file');
archivePath = internalRecipeFile;
} else {
debug('[ServerApi::getRecipePackage] Downloading recipe from server');
archivePath = tempArchivePath;
const packageUrl = `${apiBase()}/recipes/download/${recipeId}`;
const res = await window.fetch(packageUrl);
debug('Recipe downloaded', recipeId);
const blob = await res.blob();
const buffer = await blob.arrayBuffer();
writeFileSync(tempArchivePath, Buffer.from(buffer));
}
debug(archivePath);
await sleep(10);
// @ts-expect-error No overload matches this call.
await tar.x({
file: archivePath,
cwd: recipeTempDirectory,
preservePaths: true,
unlink: true,
preserveOwner: false,
onwarn: x => debug('warn', recipeId, x),
});
await sleep(10);
const { id } = readJsonSync(join(recipeTempDirectory, 'package.json'));
const recipeDirectory = join(recipesDirectory, id);
copySync(recipeTempDirectory, recipeDirectory);
removeSync(recipeTempDirectory);
removeSync(join(recipesDirectory, recipeId, 'recipe.tar.gz'));
return id;
}
// Health Check
async healthCheck() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(
`${apiBase(false)}/health`,
{
method: 'GET',
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
debug('ServerApi::healthCheck resolves');
}
async getLegacyServices() {
const file = userDataPath('settings', 'services.json');
try {
const config = readJsonSync(file);
if (Object.prototype.hasOwnProperty.call(config, 'services')) {
const services = await Promise.all(
config.services.map(async (s: { service: any }) => {
const service = s;
const request = await sendAuthRequest(
`${apiBase()}/recipes/${s.service}`,
);
if (request.status === 200) {
const data = await request.json();
// @ts-expect-error Property 'recipe' does not exist on type '{ service: any; }'.
service.recipe = new RecipePreviewModel(data);
}
return service;
}),
);
debug('ServerApi::getLegacyServices resolves', services);
return services;
}
} catch {
console.error('ServerApi::getLegacyServices no config found');
}
return [];
}
// Helper
async _mapServiceModels(services: any[]) {
const recipes = services.map((s: { recipeId: string }) => s.recipeId);
await this._bulkRecipeCheck(recipes);
return Promise.all(
services.map(async (service: any) => this._prepareServiceModel(service)),
);
/* eslint-enable no-return-await */
}
async _prepareServiceModel(service: { recipeId: string }) {
try {
const recipe = this.recipes.find(r => r.id === service.recipeId);
if (!recipe) {
console.warn(`Recipe ${service.recipeId} not loaded`);
return null;
}
return new ServiceModel(service, recipe);
} catch (error) {
debug(error);
return null;
}
}
async _bulkRecipeCheck(unfilteredRecipes: string[]) {
// Filter recipe duplicates as we don't need to download 3 Slack recipes
const recipes = unfilteredRecipes.filter(
(elem: string, pos: number, arr: string[]) => arr.indexOf(elem) === pos,
);
return Promise.all(
recipes.map(async (recipeId: string) => {
let recipe = this.recipes.find(r => r.id === recipeId);
if (!recipe) {
console.warn(
`Recipe '${recipeId}' not installed, trying to fetch from server`,
);
await this.getRecipePackage(recipeId);
debug('Rerun ServerAPI::getInstalledRecipes');
await this.getInstalledRecipes();
recipe = this.recipes.find(r => r.id === recipeId);
if (!recipe) {
console.warn(`Could not load recipe ${recipeId}`);
return null;
}
}
return recipe;
}),
).catch(error => console.error("Can't load recipe", error));
}
_mapRecipePreviewModel(recipes: IRecipePreview[]) {
return recipes
.map(recipe => {
try {
return new RecipePreviewModel(recipe);
} catch (error) {
console.error(error);
return null;
}
})
.filter(Boolean);
}
_getDevRecipes() {
const recipesDirectory = getDevRecipeDirectory();
try {
const paths = readdirSync(recipesDirectory).filter(
file =>
statSync(join(recipesDirectory, file)).isDirectory() &&
file !== 'temp',
);
const recipes = paths
.map(id => {
try {
// eslint-disable-next-line import/no-dynamic-require
const Recipe = require(id)(RecipeModel);
return new Recipe(loadRecipeConfig(id));
} catch (error) {
console.error(error);
}
return false;
})
.filter(recipe => recipe.id)
.map(data => {
const recipe = data;
recipe.icons = {
svg: `${recipe.path}/icon.svg`,
};
recipe.local = true;
return data;
});
return recipes;
} catch {
debug('Could not load dev recipes');
return false;
}
}
}
|