-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathplugins.service.ts
executable file
·1521 lines (1321 loc) · 51.5 KB
/
plugins.service.ts
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execSync, fork, spawn } from 'child_process';
import { EventEmitter } from 'events';
import {
arch,
cpus,
platform,
userInfo,
} from 'os';
import {
basename,
delimiter,
dirname,
join,
resolve,
sep,
} from 'path';
import { HttpService } from '@nestjs/axios';
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import axios from 'axios';
import {
cyan,
green,
red,
yellow,
} from 'bash-color';
import {
access,
constants,
createFile,
ensureDir,
existsSync,
pathExists,
pathExistsSync,
readFile,
readJson,
readdir,
realpath,
remove,
stat,
} from 'fs-extra';
import { orderBy, uniq } from 'lodash';
import * as NodeCache from 'node-cache';
import * as pLimit from 'p-limit';
import {
gt,
lt,
parse,
satisfies,
} from 'semver';
import { ConfigService, HomebridgeConfig } from '../../core/config/config.service';
import { Logger } from '../../core/logger/logger.service';
import { NodePtyService } from '../../core/node-pty/node-pty.service';
import { HomebridgeUpdateActionDto, PluginActionDto } from './plugins.dto';
import {
HomebridgePlugin,
INpmRegistryModule,
INpmSearchResults,
IPackageJson,
} from './types';
import { HomebridgePluginUiMetadata, HomebridgePluginVersions, PluginAlias } from './types';
@Injectable()
export class PluginsService {
private static readonly PLUGIN_IDENTIFIER_PATTERN = /^((@[\w-]*)\/)?(homebridge-[\w-]*)$/;
private npm: Array<string> = this.getNpmPath();
private paths: Array<string> = this.getBasePaths();
// installed plugin cache
private installedPlugins: HomebridgePlugin[];
// npm package cache
private npmPackage: HomebridgePlugin;
// verified plugins cache
private verifiedPlugins: string[] = [];
private verifiedPluginsIcons: { [key: string]: string } = {};
private verifiedPluginsIconsPrefix = 'https://raw.githubusercontent.com/homebridge/verified/latest/';
private verifiedPluginsJson = 'https://raw.githubusercontent.com/homebridge/verified/latest/verified-plugins.json';
private verifiedPluginsIconsJson = 'https://raw.githubusercontent.com/homebridge/verified/latest/plugin-icons.json';
// misc schemas
private miscSchemas = {
// 'homebridge-abcd': path.join(process.env.UIX_BASE_PATH, 'misc-schemas', 'abcd'),
};
// create a cache for storing plugin package.json from npm
private npmPluginCache = new NodeCache({ stdTTL: 300 });
// create a cache for storing plugin alias
private pluginAliasCache = new NodeCache({ stdTTL: 86400 });
private verifiedPluginsRetryTimeout: NodeJS.Timeout;
// these plugins are legacy Homebridge UI plugins / forks of this UI and will cause conflicts
// or have post install scripts that alter the users system without user interaction
private searchResultBlacklist = [
'homebridge-config-ui',
'homebridge-config-ui-rdp',
'homebridge-rocket-smart-home-ui',
'homebridge-ui',
'homebridge-to-hoobs',
'homebridge-server',
];
/**
* Define the alias / type some plugins without a schema where the extract method does not work
*/
private pluginAliasHints = {
'homebridge-broadlink-rm-pro': {
pluginAlias: 'BroadlinkRM',
pluginType: 'platform',
},
};
constructor(
private httpService: HttpService,
private nodePtyService: NodePtyService,
private logger: Logger,
private configService: ConfigService,
) {
/**
* The "timeout" option on axios is the response timeout
* If the user has no internet, the dns lookup may take a long time to timeout
* As the dns lookup timeout is not configurable in Node.js, this interceptor
* will cancel the request after 15 seconds.
*/
this.httpService.axiosRef.interceptors.request.use((config) => {
const source = axios.CancelToken.source();
config.cancelToken = source.token;
setTimeout(() => {
source.cancel('Timeout: request took more than 15 seconds');
}, 15000);
return config;
});
// initial verified plugins load
this.loadVerifiedPluginsList();
// update the verified plugins list every 12 hours
setInterval(this.loadVerifiedPluginsList.bind(this), 60000 * 60 * 12);
}
/**
* Return an array of plugins currently installed
*/
public async getInstalledPlugins(): Promise<HomebridgePlugin[]> {
const plugins: HomebridgePlugin[] = [];
const modules = await this.getInstalledModules();
const disabledPlugins = await this.getDisabledPlugins();
// filter out non-homebridge plugins by name
const homebridgePlugins = modules
.filter(module => (module.name.indexOf('homebridge-') === 0) || this.isScopedPlugin(module.name))
.filter(module => pathExistsSync(join(module.installPath, 'package.json')));
// limit lookup concurrency to number of cpu cores
const limit = pLimit(cpus().length);
await Promise.all(homebridgePlugins.map(async (pkg) => {
return limit(async () => {
try {
const pjson: IPackageJson = await readJson(join(pkg.installPath, 'package.json'));
// check each plugin has the 'homebridge-plugin' keyword
if (pjson.keywords && pjson.keywords.includes('homebridge-plugin')) {
// parse the package.json for each plugin
const plugin = await this.parsePackageJson(pjson, pkg.path);
// check if the plugin has been disabled
plugin.disabled = disabledPlugins.includes(plugin.name);
// filter out duplicate plugins and give preference to non-global plugins
if (!plugins.find(x => plugin.name === x.name)) {
plugins.push(plugin);
} else if (!plugin.globalInstall && plugins.find(x => plugin.name === x.name && x.globalInstall === true)) {
const index = plugins.findIndex(x => plugin.name === x.name && x.globalInstall === true);
plugins[index] = plugin;
}
}
} catch (e) {
this.logger.error(`Failed to parse plugin "${pkg.name}": ${e.message}`);
}
});
}));
this.installedPlugins = plugins;
return orderBy(plugins, [(resultItem: HomebridgePlugin) => { return resultItem.name === this.configService.name; }, 'updateAvailable', 'betaUpdateAvailable', 'name'], ['desc', 'desc', 'desc', 'asc']);
}
/**
* Returns an array of out-of-date plugins
*/
public async getOutOfDatePlugins(): Promise<HomebridgePlugin[]> {
const plugins = await this.getInstalledPlugins();
return plugins.filter(x => x.updateAvailable || x.betaUpdateAvailable);
}
/**
* Lookup a single plugin in the npm registry
* @param pluginName
*/
public async lookupPlugin(pluginName: string): Promise<HomebridgePlugin> {
if (!PluginsService.PLUGIN_IDENTIFIER_PATTERN.test(pluginName)) {
throw new BadRequestException('Invalid plugin name.');
}
const lookup = await this.searchNpmRegistrySingle(pluginName);
if (!lookup.length) {
throw new NotFoundException();
}
return lookup[0];
}
public async getAvailablePluginVersions(pluginName: string): Promise<HomebridgePluginVersions> {
if (!PluginsService.PLUGIN_IDENTIFIER_PATTERN.test(pluginName) && pluginName !== 'homebridge') {
throw new BadRequestException('Invalid plugin name.');
}
try {
const fromCache = this.npmPluginCache.get(`lookup-${pluginName}`);
const pkg: INpmRegistryModule = fromCache || (await (
this.httpService.get(`https://registry.npmjs.org/${encodeURIComponent(pluginName).replace(/%40/g, '@')}`, {
headers: {
'accept': 'application/vnd.npm.install-v1+json', // only return minimal information
},
}).toPromise()
)).data;
if (!fromCache) {
this.npmPluginCache.set(`lookup-${pluginName}`, pkg, 60);
}
return {
tags: pkg['dist-tags'],
versions: Object.keys(pkg.versions),
};
} catch (e) {
throw new NotFoundException();
}
}
/**
* Search the npm registry for homebridge plugins
* @param query
*/
public async searchNpmRegistry(query: string): Promise<HomebridgePlugin[]> {
if (!this.installedPlugins) {
await this.getInstalledPlugins();
}
const q = ((!query || !query.length) ? '' : query + '+') + 'keywords:homebridge-plugin+not:deprecated&size=30';
let searchResults: INpmSearchResults;
try {
searchResults = (await this.httpService.get(`https://registry.npmjs.org/-/v1/search?text=${q}`).toPromise()).data;
} catch (e) {
this.logger.error(`Failed to search the npm registry - "${e.message}" - see https://homebridge.io/w/JJSz6 for help.`);
throw new InternalServerErrorException(`Failed to search the npm registry - "${e.message}" - see logs.`);
}
const result: HomebridgePlugin[] = searchResults.objects
.filter(x => x.package.name.indexOf('homebridge-') === 0 || this.isScopedPlugin(x.package.name))
.filter(x => !this.searchResultBlacklist.includes(x.package.name))
.map((pkg) => {
let plugin: HomebridgePlugin = {
name: pkg.package.name,
private: false,
};
// see if the plugin is already installed
const isInstalled = this.installedPlugins.find(x => x.name === plugin.name);
if (isInstalled) {
plugin = isInstalled;
plugin.lastUpdated = pkg.package.date;
return plugin;
}
// it's not installed; finish building the response
plugin.publicPackage = true;
plugin.installedVersion = null;
plugin.latestVersion = pkg.package.version;
plugin.lastUpdated = pkg.package.date;
plugin.description = (pkg.package.description) ?
pkg.package.description.replace(/\(?(?:https?|ftp):\/\/[\n\S]+/g, '').trim() : pkg.package.name;
plugin.links = pkg.package.links;
plugin.author = (pkg.package.publisher) ? pkg.package.publisher.username : null;
plugin.verifiedPlugin = this.verifiedPlugins.includes(pkg.package.name);
plugin.icon = this.verifiedPluginsIcons[pkg.package.name]
? `${this.verifiedPluginsIconsPrefix}${this.verifiedPluginsIcons[pkg.package.name]}`
: null;
return plugin;
});
if (
!result.length
&& (query.indexOf('homebridge-') === 0 || this.isScopedPlugin(query))
&& !this.searchResultBlacklist.includes(query.toLowerCase())
) {
try {
return await this.searchNpmRegistrySingle(query.toLowerCase());
} catch (err) {
throw err;
}
}
return orderBy(result, ['verifiedPlugin'], ['desc']);
}
/**
* Get a single plugin from the registry using its exact name
* Used as a fallback if the search queries are not finding the desired plugin
* @param query
*/
async searchNpmRegistrySingle(query: string): Promise<HomebridgePlugin[]> {
try {
const fromCache = this.npmPluginCache.get(`lookup-${query}`);
const pkg: INpmRegistryModule = fromCache || (await (
this.httpService.get(`https://registry.npmjs.org/${encodeURIComponent(query).replace(/%40/g, '@')}`).toPromise()
)).data;
if (!fromCache) {
this.npmPluginCache.set(`lookup-${query}`, pkg, 60);
}
if (!pkg.keywords || !pkg.keywords.includes('homebridge-plugin')) {
return [];
}
let plugin: HomebridgePlugin;
// see if the plugin is already installed
if (!this.installedPlugins) await this.getInstalledPlugins();
const isInstalled = this.installedPlugins.find(x => x.name === pkg.name);
if (isInstalled) {
plugin = isInstalled;
plugin.lastUpdated = pkg.time.modified;
return [plugin];
}
plugin = {
name: pkg.name,
private: false,
description: (pkg.description) ?
pkg.description.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '').trim() : pkg.name,
verifiedPlugin: this.verifiedPlugins.includes(pkg.name),
icon: this.verifiedPluginsIcons[pkg.name],
} as HomebridgePlugin;
// it's not installed; finish building the response
plugin.publicPackage = true;
plugin.latestVersion = pkg['dist-tags'] ? pkg['dist-tags'].latest : undefined;
plugin.lastUpdated = pkg.time.modified;
plugin.updateAvailable = false;
plugin.betaUpdateAvailable = false;
plugin.links = {
npm: `https://www.npmjs.com/package/${plugin.name}`,
homepage: pkg.homepage,
bugs: typeof pkg.bugs === 'object' && pkg.bugs?.url ? pkg.bugs.url : null,
};
plugin.author = (pkg.maintainers.length) ? pkg.maintainers[0].name : null;
plugin.verifiedPlugin = this.verifiedPlugins.includes(pkg.name);
plugin.icon = this.verifiedPluginsIcons[pkg.name]
? `${this.verifiedPluginsIconsPrefix}${this.verifiedPluginsIcons[pkg.name]}`
: null;
return [plugin];
} catch (e) {
if (e.response?.status !== 404) {
this.logger.error(`Failed to search the npm registry - "${e.message}" - see https://homebridge.io/w/JJSz6 for help.`);
}
return [];
}
}
/**
* Manage a plugin, install, update or uninstall it
* @param action
* @param pluginAction
* @param client
*/
async managePlugin(action: 'install' | 'uninstall', pluginAction: PluginActionDto, client: EventEmitter) {
pluginAction.version = pluginAction.version || 'latest';
// prevent uninstalling self
if (action === 'uninstall' && pluginAction.name === this.configService.name) {
throw new Error(`Cannot uninstall ${pluginAction.name} from ${this.configService.name}.`);
}
// legacy support for offline docker updates
if (pluginAction.name === this.configService.name && this.configService.dockerOfflineUpdate && pluginAction.version === 'latest') {
await this.updateSelfOffline(client);
return true;
}
// convert 'latest' into a real version
if (action === 'install' && pluginAction.version === 'latest') {
pluginAction.version = await this.getNpmModuleLatestVersion(pluginAction.name);
}
// set default install path
let installPath = (this.configService.customPluginPath) ?
this.configService.customPluginPath : this.installedPlugins.find(x => x.name === this.configService.name).installPath;
// check if the plugin is already installed
await this.getInstalledPlugins();
// check if the plugin is currently installed
const existingPlugin = this.installedPlugins.find(x => x.name === pluginAction.name);
// if the plugin is already installed, match the installation path
if (existingPlugin) {
installPath = existingPlugin.installPath;
}
// homebridge-config-ui-x specific actions
if (action === 'install' && pluginAction.name === this.configService.name && await this.isUiUpdateBundleAvailable(pluginAction)) {
try {
await this.doUiBundleUpdate(pluginAction, client);
return true;
} catch (e) {
client.emit('stdout', yellow('\r\nBundled update failed. Trying regular update using npm.\r\n\r\n'));
}
// show a warning if updating homebridge-config-ui-x on Raspberry Pi 1 / Zero
if (cpus().length === 1 && arch() === 'arm') {
client.emit('stdout', yellow('***************************************************************\r\n'));
client.emit('stdout', yellow(`Please be patient while ${this.configService.name} updates.\r\n`));
client.emit('stdout', yellow('This process may take 5-15 minutes to complete on your device.\r\n'));
client.emit('stdout', yellow('***************************************************************\r\n\r\n'));
}
}
// if the plugin is verified, check to see if we can do a bundled update
if (action === 'install' && await this.isPluginBundleAvailable(pluginAction)) {
try {
await this.doPluginBundleUpdate(pluginAction, client);
return true;
} catch (e) {
client.emit('stdout', yellow('\r\nBundled install / update could not complete. Trying regular install / update using npm.\r\n\r\n'));
}
}
// prepare flags for npm command
const installOptions: Array<string> = [];
// check to see if custom plugin path is using a package.json file
if (
installPath === this.configService.customPluginPath &&
!(action === 'uninstall' && this.configService.usePnpm) &&
await pathExists(resolve(installPath, '../package.json'))
) {
installOptions.push('--save');
}
// install path is one level up
installPath = resolve(installPath, '../');
// set global flag
if (!this.configService.customPluginPath || platform() === 'win32' || existingPlugin?.globalInstall === true) {
installOptions.push('-g');
}
const npmPluginLabel = action === 'uninstall' ? pluginAction.name : `${pluginAction.name}@${pluginAction.version}`;
try {
await this.runNpmCommand(
[...this.npm, action, ...installOptions, npmPluginLabel],
installPath,
client,
pluginAction.termCols,
pluginAction.termRows,
);
// ensure the custom plugin dir was not deleted
await this.ensureCustomPluginDirExists();
return true;
} catch (e) {
if (pluginAction.name === this.configService.name) {
client.emit('stdout', yellow('\r\nCleaning up npm cache, please wait...\r\n'));
await this.cleanNpmCache();
client.emit('stdout', yellow(`npm cache cleared, please try updating ${this.configService.name} again.\r\n`));
}
throw e;
}
}
/**
* Gets the Homebridge package details
*/
public async getHomebridgePackage() {
// try load from the "homebridgePackagePath" option first
if (this.configService.ui.homebridgePackagePath) {
const pjsonPath = join(this.configService.ui.homebridgePackagePath, 'package.json');
if (await pathExists(pjsonPath)) {
try {
return await this.parsePackageJson(await readJson(pjsonPath), this.configService.ui.homebridgePackagePath);
} catch (err) {
throw err;
}
} else {
this.logger.error(`"homebridgePath" (${this.configService.ui.homebridgePackagePath}) does not exist`);
}
}
const modules = await this.getInstalledModules();
const homebridgeInstalls = modules.filter(x => x.name === 'homebridge');
if (homebridgeInstalls.length > 1) {
this.logger.warn('Multiple Instances Of Homebridge Found Installed - see https://homebridge.io/w/JJSgm for help.');
homebridgeInstalls.forEach((instance) => {
this.logger.warn(instance.installPath);
});
}
if (!homebridgeInstalls.length) {
this.configService.hbServiceUiRestartRequired = true;
this.logger.error('Unable To Find Homebridge Installation - see https://homebridge.io/w/JJSgZ for help.');
throw new Error('Unable To Find Homebridge Installation');
}
const homebridgeModule = homebridgeInstalls[0];
const pjson: IPackageJson = await readJson(join(homebridgeModule.installPath, 'package.json'));
const homebridge = await this.parsePackageJson(pjson, homebridgeModule.path);
if (!homebridge.latestVersion) {
return homebridge;
}
const homebridgeVersion = parse(homebridge.installedVersion);
// show beta updates if the user is currently running a beta release
if (homebridgeVersion.prerelease[0] === 'beta' && gt(homebridge.installedVersion, homebridge.latestVersion)) {
const versions = await this.getAvailablePluginVersions('homebridge');
if (versions.tags.beta && gt(versions.tags.beta, homebridge.installedVersion)) {
homebridge.updateAvailable = false;
homebridge.betaUpdateAvailable = true;
homebridge.latestVersion = versions.tags.beta;
}
}
this.configService.homebridgeVersion = homebridge.installedVersion;
return homebridge;
}
/**
* Updates the Homebridge package
*/
public async updateHomebridgePackage(homebridgeUpdateAction: HomebridgeUpdateActionDto, client: EventEmitter) {
const homebridge = await this.getHomebridgePackage();
homebridgeUpdateAction.version = homebridgeUpdateAction.version || 'latest';
if (homebridgeUpdateAction.version === 'latest' && homebridge.latestVersion) {
homebridgeUpdateAction.version = homebridge.latestVersion;
}
// get the currently installed
let installPath = homebridge.installPath;
// prepare flags for npm command
const installOptions: Array<string> = [];
// check to see if custom plugin path is using a package.json file
if (installPath === this.configService.customPluginPath && await pathExists(resolve(installPath, '../package.json'))) {
installOptions.push('--save');
}
installPath = resolve(installPath, '../');
// set global flag
if (homebridge.globalInstall || platform() === 'win32') {
installOptions.push('-g');
}
await this.runNpmCommand(
[...this.npm, 'install', ...installOptions, `${homebridge.name}@${homebridgeUpdateAction.version}`],
installPath,
client,
homebridgeUpdateAction.termCols,
homebridgeUpdateAction.termRows,
);
return true;
}
/**
* Gets the Homebridge UI package details
*/
public async getHomebridgeUiPackage(): Promise<HomebridgePlugin> {
const plugins = await this.getInstalledPlugins();
return plugins.find((x: HomebridgePlugin) => x.name === this.configService.name);
}
/**
* Gets the npm module details
*/
public async getNpmPackage() {
if (this.npmPackage) {
return this.npmPackage;
} else {
const modules = await this.getInstalledModules();
const npmPkg = modules.find(x => x.name === 'npm');
if (!npmPkg) {
throw new Error('Could not find npm package');
}
const pjson: IPackageJson = await readJson(join(npmPkg.installPath, 'package.json'));
const npm = await this.parsePackageJson(pjson, npmPkg.path) as HomebridgePlugin & { showUpdateWarning?: boolean };
// show the update warning if the installed version is below the minimum recommended
// (bwp91) I set this to 9.5.0 to match a minimum node version of 18.15.0
npm.showUpdateWarning = lt(npm.installedVersion, '9.5.0');
this.npmPackage = npm;
return npm;
}
}
/**
* Check to see if a plugin update bundle is available
* @param pluginAction
*/
public async isPluginBundleAvailable(pluginAction: PluginActionDto) {
if (
this.configService.usePluginBundles === true &&
this.configService.customPluginPath &&
this.configService.strictPluginResolution &&
pluginAction.name !== this.configService.name &&
pluginAction.version !== 'latest'
) {
try {
await this.httpService.head(`/~https://github.com/homebridge/plugin-repo/releases/download/v1/${pluginAction.name.replace('/', '@')}-${pluginAction.version}.sha256`).toPromise();
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}
/**
* Update a plugin using the bundle
* @param pluginAction
* @param client
*/
public async doPluginBundleUpdate(pluginAction: PluginActionDto, client: EventEmitter) {
const pluginUpgradeInstallScriptPath = join(process.env.UIX_BASE_PATH, 'plugin-upgrade-install.sh');
await this.runNpmCommand(
[pluginUpgradeInstallScriptPath, pluginAction.name, pluginAction.version, this.configService.customPluginPath],
this.configService.storagePath,
client,
pluginAction.termCols,
pluginAction.termRows,
);
return true;
}
/**
* Check if a UI Update bundle is available for the given version
*/
public async isUiUpdateBundleAvailable(pluginAction: PluginActionDto): Promise<boolean> {
if (
[
'/usr/local/lib/node_modules',
'/usr/lib/node_modules',
'/opt/homebridge/lib/node_modules',
'/var/packages/homebridge/target/app/lib/node_modules',
].includes(dirname(process.env.UIX_BASE_PATH)) &&
pluginAction.name === this.configService.name &&
pluginAction.version !== 'latest'
) {
try {
await this.httpService.head(`/~https://github.com/homebridge/homebridge-config-ui-x/releases/download/${pluginAction.version}/homebridge-config-ui-x-${pluginAction.version}.tar.gz`).toPromise();
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}
/**
* Do a UI update from the bundle
* @param pluginAction
* @param client
*/
public async doUiBundleUpdate(pluginAction: PluginActionDto, client: EventEmitter) {
const prefix = dirname(dirname(dirname(process.env.UIX_BASE_PATH)));
const upgradeInstallScriptPath = join(process.env.UIX_BASE_PATH, 'upgrade-install.sh');
await this.runNpmCommand(
this.configService.ui.sudo ? ['npm', 'run', 'upgrade-install', '--', pluginAction.version, prefix] : [upgradeInstallScriptPath, pluginAction.version, prefix],
process.env.UIX_BASE_PATH,
client,
pluginAction.termCols,
pluginAction.termRows,
);
}
/**
* Sets a flag telling the system to update the package next time the UI is restarted
* Dependent on OS support - currently only supported by the homebridge/homebridge docker image
*/
public async updateSelfOffline(client: EventEmitter) {
client.emit('stdout', yellow(`${this.configService.name} has been scheduled to update on the next container restart.\n\r\n\r`));
await new Promise((res) => setTimeout(res, 800));
client.emit('stdout', yellow('The Docker container will now try and restart.\n\r\n\r'));
await new Promise((res) => setTimeout(res, 800));
client.emit('stdout', yellow('If you have not started the Docker container with ') +
red('--restart=always') + yellow(' you may\n\rneed to manually start the container again.\n\r\n\r'));
await new Promise((res) => setTimeout(res, 800));
client.emit('stdout', yellow('This process may take several minutes. Please be patient.\n\r'));
await new Promise((res) => setTimeout(res, 10000));
await createFile('/homebridge/.uix-upgrade-on-restart');
}
/**
* Returns the config.schema.json for the plugin
* @param pluginName
*/
public async getPluginConfigSchema(pluginName: string) {
if (!this.installedPlugins) await this.getInstalledPlugins();
const plugin = this.installedPlugins.find(x => x.name === pluginName);
if (!plugin) {
throw new NotFoundException();
}
if (!plugin.settingsSchema) {
throw new NotFoundException();
}
const schemaPath = resolve(plugin.installPath, pluginName, 'config.schema.json');
if (this.miscSchemas[pluginName] && !await pathExists(schemaPath)) {
try {
return await readJson(this.miscSchemas[pluginName]);
} catch (err) {
throw err;
}
}
let configSchema = await readJson(schemaPath);
// check to see if this plugin implements dynamic schemas
if (configSchema.dynamicSchemaVersion) {
const dynamicSchemaPath = resolve(this.configService.storagePath, `.${pluginName}-v${configSchema.dynamicSchemaVersion}.schema.json`);
this.logger.log(`[${pluginName}] dynamic schema path: ${dynamicSchemaPath}`);
if (existsSync(dynamicSchemaPath)) {
try {
configSchema = await readJson(dynamicSchemaPath);
this.logger.log(`[${pluginName}] dynamic schema loaded from: ${dynamicSchemaPath}`);
} catch (e) {
this.logger.error(`[${pluginName}] Failed to load dynamic schema at ${dynamicSchemaPath}: ${e.message}`);
}
}
}
// modify this plugins schema to set the default port number
if (pluginName === this.configService.name) {
configSchema.schema.properties.port.default = this.configService.ui.port;
// filter some options from the UI config when using service mode
if (this.configService.serviceMode) {
configSchema.layout = configSchema.layout.filter((x: any) => {
return x.ref !== 'log';
});
const advanced = configSchema.layout.find((x: any) => x.ref === 'advanced');
advanced.items = advanced.items.filter((x: any) => {
return !(x === 'sudo' || x.key === 'restart');
});
}
}
// modify homebridge-alexa to set the default pin
if (pluginName === 'homebridge-alexa') {
configSchema.schema.properties.pin.default = this.configService.homebridgeConfig.bridge.pin;
}
// add the display name from the config.json
if (plugin.displayName) {
configSchema.displayName = plugin.displayName;
}
// inject schema for _bridge child bridge setting (this is hidden, but prevents it getting removed)
const childBridgeSchema = {
type: 'object',
notitle: true,
condition: {
functionBody: 'return false',
},
properties: {
name: {
type: 'string',
},
username: {
type: 'string',
},
pin: {
type: 'string',
},
port: {
type: 'integer',
maximum: 65535,
},
setupID: {
type: 'string',
},
manufacturer: {
type: 'string',
},
firmwareRevision: {
type: 'string',
},
model: {
type: 'string',
},
},
};
if (configSchema.schema && typeof configSchema.schema.properties === 'object') {
configSchema.schema.properties._bridge = childBridgeSchema;
} else if (typeof configSchema.schema === 'object') {
configSchema.schema._bridge = childBridgeSchema;
}
return configSchema;
}
/**
* Returns the changelog from the npm package for a plugin
* @param pluginName
*/
public async getPluginChangeLog(pluginName: string) {
await this.getInstalledPlugins();
const plugin = this.installedPlugins.find(x => x.name === pluginName);
if (!plugin) {
throw new NotFoundException();
}
const changeLog = resolve(plugin.installPath, plugin.name, 'CHANGELOG.md');
if (await pathExists(changeLog)) {
return {
changelog: await readFile(changeLog, 'utf8'),
};
} else {
throw new NotFoundException();
}
}
/**
* Get the latest release notes from GitHub for a plugin
* @param pluginName
*/
public async getPluginRelease(pluginName: string) {
if (!this.installedPlugins) await this.getInstalledPlugins();
const plugin = pluginName === 'homebridge' ? await this.getHomebridgePackage() : this.installedPlugins.find(x => x.name === pluginName);
if (!plugin) {
throw new NotFoundException();
}
// Plugin must have a homepage to work out Git Repo
// Some plugins have a custom homepage, so often we can also use the bugs link too
if (!plugin.links.homepage && !plugin.links.bugs) {
throw new NotFoundException();
}
// make sure the repo is GitHub
const repoMatch = plugin.links.homepage.match(/https:\/\/github.com\/([^\/]+)\/([^\/#]+)/);
const bugsMatch = plugin.links.bugs?.match(/https:\/\/github.com\/([^\/]+)\/([^\/#]+)/);
let match: RegExpMatchArray | null = repoMatch;
if (!repoMatch) {
if (!bugsMatch) {
throw new NotFoundException();
}
match = bugsMatch;
}
// Special case for beta npm tags for homebridge, homebridge ui and all plugins
if (plugin.latestVersion?.includes('beta')) {
let betaBranch: string | undefined;
if (['homebridge-config-ui-x', 'homebridge'].includes(plugin.name)) {
// If loading a homebridge/ui beta returned pre-defined help text
// Query the list of branches for the repo, if the request doesn't work it doesn't matter too much
try {
// Find the first branch that starts with "beta"
betaBranch = (await this.httpService.get(`https://api.github.com/repos/homebridge/${plugin.name}/branches`).toPromise())
.data
.find((branch: any) => branch.name.startsWith('beta-'))
?.name;
} catch (e) {
this.logger.error(`Failed to get list of branches from GitHub: ${e.message}`);
}
}
return {
name: 'v' + plugin.latestVersion,
changelog: `Thank you for helping improve ${plugin.displayName || `\`${plugin.name}\``} by testing a beta version.\n\n` +
'You can use the Homebridge UI at any time to revert back to the stable version.\n\n' +
'Please remember this is a **beta** version, and report any issues to the GitHub repository page:\n' +
`- /~https://github.com/${repoMatch[1]}/${repoMatch[2]}/issues` +
(betaBranch ? `\n\nSee the commit history for recent changes:\n- /~https://github.com/${repoMatch[1]}/${repoMatch[2]}/commits/${betaBranch}` : ''),
};
}
try {
const release = (await this.httpService.get(`https://api.github.com/repos/${match[1]}/${match[2]}/releases/latest`).toPromise()).data;
return {
name: release.name,
changelog: release.body,
};
} catch (e) {
throw new NotFoundException();
}
}
/**
* Attempt to extract the alias from a plugin
*/
public async getPluginAlias(pluginName: string): Promise<PluginAlias> {
if (!this.installedPlugins) await this.getInstalledPlugins();
const plugin = this.installedPlugins.find(x => x.name === pluginName);
if (!plugin) {
throw new NotFoundException();
}
const fromCache: PluginAlias | undefined = this.pluginAliasCache.get(pluginName);
if (fromCache as any) {
return fromCache;
}
const output = {
pluginAlias: null,
pluginType: null,
};
if (plugin.settingsSchema) {
const schema = await this.getPluginConfigSchema(pluginName);
output.pluginAlias = schema.pluginAlias;
output.pluginType = schema.pluginType;
} else {
try {
await new Promise((res, rej) => {
const child = fork(resolve(process.env.UIX_BASE_PATH, 'extract-plugin-alias.js'), {
env: {
UIX_EXTRACT_PLUGIN_PATH: resolve(plugin.installPath, plugin.name),
},
stdio: 'ignore',
});
child.once('message', (data: any) => {
if (data.pluginAlias && data.pluginType) {
output.pluginAlias = data.pluginAlias;
output.pluginType = data.pluginType;
res(null);
} else {
rej('Invalid Response');
}
});
child.once('close', (code) => {
if (code !== 0) {
rej();
}
});
});
} catch (e) {
this.logger.debug('Failed to extract plugin alias:', e);
// fallback to the manual list, if defined for this plugin
if (this.pluginAliasHints[pluginName]) {
output.pluginAlias = this.pluginAliasHints[pluginName].pluginAlias;
output.pluginType = this.pluginAliasHints[pluginName].pluginType;
}