14 |
15 |
30 |
31 |
--------------------------------------------------------------------------------
/bin/cmds/app/install.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const Log = require('../../../lib/Log');
4 | const App = require('../../../lib/App');
5 | const AthomApi = require('../../../services/AthomApi');
6 |
7 | exports.desc = 'Install a Homey App';
8 | exports.builder = yargs => {
9 | return yargs
10 | .option('clean', {
11 | alias: 'c',
12 | type: 'boolean',
13 | default: false,
14 | })
15 | .option('skip-build', {
16 | alias: 's',
17 | type: 'boolean',
18 | default: false,
19 | });
20 | };
21 | exports.handler = async yargs => {
22 | try {
23 | const homey = await AthomApi.getActiveHomey();
24 | const app = new App(yargs.path);
25 | await app.install({
26 | homey,
27 | clean: yargs.clean,
28 | skipBuild: yargs.skipBuild,
29 | });
30 | process.exit(0);
31 | } catch (err) {
32 | if (err instanceof Error && err.stack) {
33 | Log.error(err.stack);
34 | } else {
35 | Log.error(err);
36 | }
37 | process.exit(1);
38 | }
39 | };
40 |
--------------------------------------------------------------------------------
/lib/Util.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const crypto = require('crypto');
4 |
5 | const fse = require('fs-extra');
6 |
7 | module.exports = class Util {
8 |
9 | static md5(input) {
10 | return crypto
11 | .createHash('md5')
12 | .update(input)
13 | .digest('hex');
14 | }
15 |
16 | static ellipsis(str) {
17 | if (str.length > 10) {
18 | return `${str.substr(0, 5)}...${str.substr(str.length - 5, str.length)}`;
19 | }
20 | return str;
21 | }
22 |
23 | static async getFileHash(filepath, algorithm = 'md5') {
24 | const buf = await fse.readFile(filepath);
25 |
26 | if (algorithm === 'md5') {
27 | const md5 = this.md5(buf);
28 | return md5;
29 | }
30 |
31 | throw new Error(`Unknown Algorithm: ${algorithm}`);
32 | }
33 |
34 | static parseMacToDecArray(macAddress) {
35 | const mac = [];
36 | macAddress
37 | .slice(0, 8)
38 | .split(':') // TODO - is also a valid MAC address seperator
39 | .forEach(macByte => mac.push(parseInt(macByte, 16)));
40 |
41 | return mac;
42 | }
43 |
44 | };
45 |
--------------------------------------------------------------------------------
/bin/homey.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | 'use strict';
4 |
5 | const yargs = require('yargs');
6 | const updateNotifier = require('update-notifier');
7 | const semver = require('semver');
8 |
9 | const pkg = require('../package.json');
10 | const Log = require('../lib/Log');
11 | const AthomMessage = require('../services/AthomMessage');
12 |
13 | // Ensure the minimum Node.js version is high enough
14 | const MINIMUM_NODE_VERSION = 'v16.0.0';
15 |
16 | try {
17 | if (semver.lt(process.version, MINIMUM_NODE_VERSION)) {
18 | Log(`Homey CLI requires Node.js ${MINIMUM_NODE_VERSION} or higher.\nPlease upgrade your Node.js version and try again.`);
19 | return;
20 | }
21 | } catch (err) {
22 | Log(`Failed to determine Node.js version, please make sure you're using version ${MINIMUM_NODE_VERSION} or higher.`);
23 | return;
24 | }
25 |
26 | (async () => {
27 | await AthomMessage.notify();
28 | updateNotifier({ pkg }).notify({
29 | isGlobal: true,
30 | });
31 |
32 | return yargs
33 | .commandDir('./cmds')
34 | .demandCommand()
35 | .strict()
36 | .help()
37 | .argv;
38 | })();
39 |
--------------------------------------------------------------------------------
/lib/Log.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const figures = require('figures');
4 | const colors = require('colors');
5 |
6 | module.exports = (...props) => {
7 | // Replace every prop's symbols to platform-specific symbols
8 | for (const [key, value] of Object.entries(props)) {
9 | props[key] = figures(value instanceof Error ? (value.message || value.toString()) : value);
10 | }
11 |
12 | // eslint-disable-next-line no-console
13 | console.log(...props);
14 | };
15 |
16 | module.exports.info = (...props) => {
17 | module.exports(colors.grey(...props));
18 | };
19 |
20 | module.exports.success = (...props) => {
21 | module.exports(colors.green('✓', ...props));
22 | };
23 |
24 | module.exports.warning = (...props) => {
25 | module.exports(colors.yellow('ℹ', ...props));
26 | };
27 |
28 | module.exports.error = (...props) => {
29 | // Replace Error with Error.message
30 | for (const [key, value] of Object.entries(props)) {
31 | if (value instanceof Error) {
32 | props[key] = value.message ?? value.toString();
33 | }
34 | }
35 |
36 | module.exports(colors.red('✖', ...props));
37 | };
38 |
--------------------------------------------------------------------------------
/bin/cmds/app/version.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const Log = require('../../../lib/Log');
4 | const App = require('../../../lib/App');
5 |
6 | exports.command = 'version ';
7 | exports.desc = 'Update a Homey App\'s version';
8 | exports.builder = yargs => {
9 | return yargs
10 | .positional('next', {
11 | describe: 'patch/minor/major or semver',
12 | type: 'string',
13 | })
14 | .option('changelog', {
15 | default: null,
16 | type: 'string',
17 | description: 'What\'s new in this version? Use dot-notation for translation. Example: --changelog.en "Add new feature" --changelog.de "Neue Funktionalität"',
18 | })
19 | .option('commit', {
20 | description: 'Create a git commit and tag for the new version',
21 | });
22 | };
23 | exports.handler = async yargs => {
24 | try {
25 | const app = new App(yargs.path);
26 | await app.version(yargs.next);
27 |
28 | if (yargs.changelog) {
29 | await app.changelog(yargs.changelog);
30 | }
31 |
32 | if (yargs.commit) {
33 | await app.commit(yargs.changelog);
34 | }
35 |
36 | process.exit(0);
37 | } catch (err) {
38 | Log.error(err);
39 | process.exit(1);
40 | }
41 | };
42 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Homey
2 |
3 | Command-line interface and type declarations for Homey Apps.
4 |
5 | ## Installation
6 |
7 | ```bash
8 | $ npm i -g homey
9 | ```
10 |
11 | ## Getting started
12 |
13 | To get started run:
14 | ```bash
15 | $ homey --help
16 | ```
17 |
18 | Or read the [getting started](https://apps.developer.homey.app/the-basics/getting-started) documentation.
19 |
20 | ## Homey Apps SDK Documentation
21 | Please visit https://homey.app/developer for more information.
22 |
23 | ## Useful links
24 |
25 | ### Z-Wave
26 | The `zwave` installs [homey-zwavedriver](https://www.npmjs.com/package/homey-zwavedriver).
27 |
28 | ### Zigbee
29 | The `zigbee` installs [homey-zigbeedriver](https://www.npmjs.com/package/homey-zigbeedriver).
30 |
31 | ### RF
32 | The `rf` installs [homey-rfdriver](https://www.npmjs.com/package/homey-rfdriver), and copies pairing templates to `/.homeycompose/`.
33 |
34 | ### OAuth2
35 | The `oauth2` installs [homey-oauth2app](https://github.com/athombv/node-homey-oauth2app).
36 |
37 | ### Log
38 | The `log` installs [homey-log](https://www.npmjs.com/package/homey-log). You must still require the module in the app yourself:
39 |
40 | ```
41 | const Log = require('homey-log');
42 | ```
43 |
44 | Don't forget to add the `HOMEY_LOG_URL` variable to your `env.json`.
45 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Lint
2 |
3 | # Version: 2.0.1
4 | # Modified: No
5 | #
6 | # Secrets:
7 | # - HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN
8 |
9 | # GitHub repo configuration:
10 | # 1. If you have protected branches, go to Branches > edit protected branch > enable 'Require status checks to pass before
11 | # merging' and select the 'ESLint' status check.
12 |
13 | # Note: make sure to commit package-lock.json, this is needed for `npm ci`.
14 |
15 | # Defines the trigger for this action (e.g. [pull_request, push])
16 | # For more information see: https://help.github.com/en/actions/automating-your-workflow-with-github-actions/events-that-trigger-workflows#about-workflow-events)
17 | on:
18 | workflow_dispatch:
19 | pull_request:
20 | push:
21 | branches:
22 | - master
23 |
24 | jobs:
25 | lint:
26 | name: Lint
27 | runs-on: ubuntu-latest
28 | steps:
29 | - uses: actions/checkout@v3
30 |
31 | # Setup
32 | - name: Setup Node.js
33 | uses: actions/setup-node@v3
34 | with:
35 | node-version: 16
36 | registry-url: 'https://npm.pkg.github.com'
37 |
38 | # Lint
39 | - run: |
40 | npm ci --ignore-scripts --audit=false
41 | npm run lint
42 | env:
43 | NODE_AUTH_TOKEN: ${{ secrets.HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN }}
44 |
45 |
--------------------------------------------------------------------------------
/bin/cmds/list.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const Table = require('cli-table');
4 | const colors = require('colors');
5 | const Log = require('../../lib/Log');
6 | const AthomApi = require('../../services/AthomApi');
7 |
8 | exports.desc = 'List all Homeys';
9 | exports.handler = async () => {
10 | try {
11 | const homeys = await AthomApi.getHomeys();
12 |
13 | const table = new Table({
14 | head: [
15 | 'ID',
16 | 'Name',
17 | 'Platform',
18 | 'Platform Version',
19 | 'Software Version',
20 | 'API Version',
21 | 'Language',
22 | 'Users',
23 | 'Role',
24 | 'Region',
25 | 'USB',
26 | ].map(title => colors.white.bold(title)),
27 | });
28 |
29 | homeys.sort((a, b) => {
30 | return -(a.state || '').localeCompare((b.state || ''));
31 | });
32 |
33 | homeys.forEach(homey => {
34 | table.push([
35 | homey.id,
36 | homey.name,
37 | homey.platform,
38 | homey.platformVersion,
39 | homey.softwareVersion,
40 | homey.apiVersion,
41 | homey.language,
42 | homey.users && homey.users.length,
43 | homey.role,
44 | homey.region || '-',
45 | homey.usb ? 'Yes' : '-',
46 | ].map(value => value || '-'));
47 | });
48 |
49 | Log(table.toString());
50 | process.exit(0);
51 | } catch (err) {
52 | Log.error(err.stack);
53 | process.exit(1);
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/.github/workflows/npm-version.yml:
--------------------------------------------------------------------------------
1 | name: Update Package Version
2 |
3 | # Version: 1.0.0
4 | # Modified: No
5 | # Requirements:
6 | # - A valid package.json
7 | # - The `Homey Github Actions Bot` should have `Admin` level access to the repository,
8 | # to bypass push restrictions.
9 | #
10 | # Required secrets:
11 | # - HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN
12 |
13 | on:
14 | workflow_dispatch:
15 | branches:
16 | - master
17 | inputs:
18 | newversion:
19 | type: choice
20 | description: New Version
21 | required: true
22 | default: patch
23 | options:
24 | - major
25 | - minor
26 | - patch
27 |
28 |
29 | jobs:
30 | publish:
31 | name: Publish
32 | runs-on: ubuntu-latest
33 | steps:
34 |
35 | - name: Checkout git repository
36 | uses: actions/checkout@v3
37 | with:
38 | token: ${{ secrets.HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN }}
39 |
40 | - name: Set up node 16 environment
41 | uses: actions/setup-node@v3
42 | with:
43 | node-version: 16
44 | registry-url: 'https://npm.pkg.github.com'
45 |
46 | - name: Version
47 | run: |
48 | git config --local user.email "sysadmin+githubactions@athom.com"
49 | git config --local user.name "Homey Github Actions Bot"
50 | git pull
51 | npm version ${{ github.event.inputs.newversion }}
52 | git push --follow-tags
53 |
--------------------------------------------------------------------------------
/assets/templates/app/assets/icon.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
19 |
--------------------------------------------------------------------------------
/assets/templates/app/drivers/device.mjs:
--------------------------------------------------------------------------------
1 | import Homey from 'homey';
2 |
3 | export default class MyDevice extends Homey.Device {
4 |
5 | /**
6 | * onInit is called when the device is initialized.
7 | */
8 | async onInit() {
9 | this.log('MyDevice has been initialized');
10 | }
11 |
12 | /**
13 | * onAdded is called when the user adds the device, called just after pairing.
14 | */
15 | async onAdded() {
16 | this.log('MyDevice has been added');
17 | }
18 |
19 | /**
20 | * onSettings is called when the user updates the device's settings.
21 | * @param {object} event the onSettings event data
22 | * @param {object} event.oldSettings The old settings object
23 | * @param {object} event.newSettings The new settings object
24 | * @param {string[]} event.changedKeys An array of keys changed since the previous version
25 | * @returns {Promise} return a custom message that will be displayed
26 | */
27 | async onSettings({ oldSettings, newSettings, changedKeys }) {
28 | this.log('MyDevice settings where changed');
29 | }
30 |
31 | /**
32 | * onRenamed is called when the user updates the device's name.
33 | * This method can be used this to synchronise the name to the device.
34 | * @param {string} name The new name
35 | */
36 | async onRenamed(name) {
37 | this.log('MyDevice was renamed');
38 | }
39 |
40 | /**
41 | * onDeleted is called when the user deleted the device.
42 | */
43 | async onDeleted() {
44 | this.log('MyDevice has been deleted');
45 | }
46 |
47 | };
48 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "homey",
3 | "version": "3.10.0",
4 | "description": "Command-line interface and type declarations for Homey Apps",
5 | "main": "bin/homey.js",
6 | "files": [
7 | "/assets",
8 | "/bin",
9 | "/lib",
10 | "/sdk",
11 | "/services",
12 | "/config.js"
13 | ],
14 | "scripts": {
15 | "lint": "eslint ."
16 | },
17 | "bin": {
18 | "homey": "bin/homey.js"
19 | },
20 | "engines": {
21 | "node": ">=18.0.0"
22 | },
23 | "author": "Athom B.V.",
24 | "license": "ISC",
25 | "readme": "README.md",
26 | "dependencies": {
27 | "cli-table": "^0.3.11",
28 | "colors": "^1.1.2 <=1.4.0",
29 | "deepmerge": "^4.3.1",
30 | "dockerode": "^4.0.2",
31 | "eslint": "^6.8.0",
32 | "express": "^4.19.2",
33 | "figures": "^3.2.0",
34 | "filesize": "^6.4.0",
35 | "fs-extra": "^10.1.0",
36 | "get-port": "^5.1.1",
37 | "homey-api": "^3.14.20",
38 | "homey-lib": "^2.39.2",
39 | "ignore-walk": "^3.0.3",
40 | "inquirer": "8.1.2",
41 | "is-wsl": "^2.2.0",
42 | "node-fetch": "^2.7.0",
43 | "object-path": "^0.11.4",
44 | "open": "^8.4.2",
45 | "openai": "^4.52.7",
46 | "p-queue": "^6.6.2",
47 | "semver": "^7.6.0",
48 | "sharp": "^0.33.4",
49 | "socket.io": "^4.7.5",
50 | "socket.io-client": "^4.7.5",
51 | "tar-fs": "^2.1.1",
52 | "tmp-promise": "^3.0.3",
53 | "underscore": "^1.13.6",
54 | "update-notifier": "^5.1.0",
55 | "yargs": "^17.7.2"
56 | },
57 | "devDependencies": {
58 | "eslint-config-athom": "^2.1.1"
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/assets/templates/app/drivers/device.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const Homey = require('homey');
4 |
5 | module.exports = class MyDevice extends Homey.Device {
6 |
7 | /**
8 | * onInit is called when the device is initialized.
9 | */
10 | async onInit() {
11 | this.log('MyDevice has been initialized');
12 | }
13 |
14 | /**
15 | * onAdded is called when the user adds the device, called just after pairing.
16 | */
17 | async onAdded() {
18 | this.log('MyDevice has been added');
19 | }
20 |
21 | /**
22 | * onSettings is called when the user updates the device's settings.
23 | * @param {object} event the onSettings event data
24 | * @param {object} event.oldSettings The old settings object
25 | * @param {object} event.newSettings The new settings object
26 | * @param {string[]} event.changedKeys An array of keys changed since the previous version
27 | * @returns {Promise} return a custom message that will be displayed
28 | */
29 | async onSettings({ oldSettings, newSettings, changedKeys }) {
30 | this.log('MyDevice settings where changed');
31 | }
32 |
33 | /**
34 | * onRenamed is called when the user updates the device's name.
35 | * This method can be used this to synchronise the name to the device.
36 | * @param {string} name The new name
37 | */
38 | async onRenamed(name) {
39 | this.log('MyDevice was renamed');
40 | }
41 |
42 | /**
43 | * onDeleted is called when the user deleted the device.
44 | */
45 | async onDeleted() {
46 | this.log('MyDevice has been deleted');
47 | }
48 |
49 | };
50 |
--------------------------------------------------------------------------------
/assets/templates/app/.github/workflows/homey-app-version.yml:
--------------------------------------------------------------------------------
1 | name: Update Homey App Version
2 | on:
3 | workflow_dispatch:
4 | inputs:
5 | version:
6 | type: choice
7 | description: Version
8 | required: true
9 | default: patch
10 | options:
11 | - major
12 | - minor
13 | - patch
14 | changelog:
15 | type: string
16 | description: Changelog
17 | required: true
18 |
19 | # Needed in order to push the commit and create a release
20 | permissions:
21 | contents: write
22 |
23 | jobs:
24 | main:
25 | name: Update Homey App Version
26 | runs-on: ubuntu-latest
27 | steps:
28 | - uses: actions/checkout@v4
29 |
30 | - name: Update Homey App Version
31 | uses: athombv/github-action-homey-app-version@master
32 | id: update_app_version
33 | with:
34 | version: ${{ inputs.version }}
35 | changelog: ${{ inputs.changelog }}
36 |
37 | - name: Commit & Push
38 | run: |
39 | git config --local user.name "github-actions[bot]"
40 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
41 |
42 | git add -A
43 | git commit -m "Update Homey App Version to v${{ steps.update_app_version.outputs.version }}"
44 | git tag "v${{ steps.update_app_version.outputs.version }}"
45 |
46 | git push origin HEAD --tags
47 | gh release create "v${{ steps.update_app_version.outputs.version }}" -t "v${{ steps.update_app_version.outputs.version }}" --notes "" --generate-notes
48 | env:
49 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
50 | GH_TOKEN: ${{ github.token }}
51 |
--------------------------------------------------------------------------------
/assets/templates/app/drivers/device.ts:
--------------------------------------------------------------------------------
1 | import Homey from 'homey';
2 |
3 | module.exports = class MyDevice extends Homey.Device {
4 |
5 | /**
6 | * onInit is called when the device is initialized.
7 | */
8 | async onInit() {
9 | this.log('MyDevice has been initialized');
10 | }
11 |
12 | /**
13 | * onAdded is called when the user adds the device, called just after pairing.
14 | */
15 | async onAdded() {
16 | this.log('MyDevice has been added');
17 | }
18 |
19 | /**
20 | * onSettings is called when the user updates the device's settings.
21 | * @param {object} event the onSettings event data
22 | * @param {object} event.oldSettings The old settings object
23 | * @param {object} event.newSettings The new settings object
24 | * @param {string[]} event.changedKeys An array of keys changed since the previous version
25 | * @returns {Promise} return a custom message that will be displayed
26 | */
27 | async onSettings({
28 | oldSettings,
29 | newSettings,
30 | changedKeys,
31 | }: {
32 | oldSettings: { [key: string]: boolean | string | number | undefined | null };
33 | newSettings: { [key: string]: boolean | string | number | undefined | null };
34 | changedKeys: string[];
35 | }): Promise {
36 | this.log("MyDevice settings where changed");
37 | }
38 |
39 | /**
40 | * onRenamed is called when the user updates the device's name.
41 | * This method can be used this to synchronise the name to the device.
42 | * @param {string} name The new name
43 | */
44 | async onRenamed(name: string) {
45 | this.log('MyDevice was renamed');
46 | }
47 |
48 | /**
49 | * onDeleted is called when the user deleted the device.
50 | */
51 | async onDeleted() {
52 | this.log('MyDevice has been deleted');
53 | }
54 |
55 | };
56 |
--------------------------------------------------------------------------------
/bin/cmds/app/translate.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const colors = require('colors');
4 |
5 | const Log = require('../../../lib/Log');
6 | const App = require('../../../lib/App');
7 |
8 | exports.desc = 'Translate a Homey App with OpenAI';
9 | exports.builder = yargs => {
10 | return yargs
11 | .option('languages', {
12 | default: ['nl', 'da', 'de', 'es', 'fr', 'it', 'no', 'sv', 'pl', 'ru', 'ko', 'ar'].join(','),
13 | type: 'string',
14 | description: 'Comma-seperated list of languages to translate to.',
15 | })
16 | .option('api-key', {
17 | default: process.env.OPENAI_API_KEY,
18 | type: 'string',
19 | description: 'OpenAI API key. You can create an API Key on https://platform.openai.com/api-keys.',
20 | })
21 | .option('model', {
22 | default: 'gpt-4o',
23 | type: 'string',
24 | description: 'OpenAI model to use.',
25 | })
26 | .option('file', {
27 | type: 'string',
28 | description: 'Absolute path to a single file to translate, instead of automatically translating the entire folder.',
29 | });
30 | };
31 | exports.handler = async yargs => {
32 | try {
33 | const app = new App(yargs.path);
34 | await app.translateWithOpenAI({
35 | languages: yargs.languages.split(',').map(lang => lang.trim()),
36 | apiKey: yargs.apiKey,
37 | model: yargs.model,
38 | file: yargs.file,
39 | });
40 | await app.preprocess({
41 | copyAppProductionDependencies: false,
42 | });
43 | await app.validate({
44 | level: yargs.level,
45 | });
46 |
47 | Log('');
48 | Log(colors.yellow('The app has been translated using AI, so results may vary. Please check every file manually before committing.'));
49 |
50 | process.exit(0);
51 | } catch (err) {
52 | Log.error(err);
53 | process.exit(1);
54 | }
55 | };
56 |
--------------------------------------------------------------------------------
/lib/AthomMessage.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const fetch = require('node-fetch');
4 | const colors = require('colors');
5 | const Table = require('cli-table');
6 |
7 | const Log = require('./Log');
8 | const Settings = require('../services/Settings');
9 | const {
10 | ATHOM_CLI_MESSAGE_URL,
11 | } = require('../config');
12 |
13 | const CACHE_HOURS = 12;
14 |
15 | class AthomMessage {
16 |
17 | async notify() {
18 | try {
19 | const now = new Date();
20 | let lastCheck = await Settings.get('athomMessageLastCheck');
21 | if (lastCheck === null) {
22 | lastCheck = new Date(2018, 1, 14);
23 | } else {
24 | lastCheck = new Date(lastCheck);
25 | }
26 |
27 | const hours = Math.abs(now - lastCheck) / 36e5;
28 | if (hours > CACHE_HOURS) {
29 | const res = await fetch(ATHOM_CLI_MESSAGE_URL, { timeout: 1000 });
30 | if (!res.ok) return undefined;
31 |
32 | const json = await res.json();
33 |
34 | await Settings.set('athomMessageCached', json.message);
35 | await Settings.set('athomMessageLastCheck', now.toString());
36 | }
37 | } catch (err) {
38 | return undefined;
39 | }
40 |
41 | return this._showMessage();
42 | }
43 |
44 | async _showMessage() {
45 | try {
46 | let message = await Settings.get('athomMessageCached');
47 | if (message) {
48 | message = AthomMessage.formatMessage(message);
49 |
50 | const table = new Table();
51 | table.push([message]);
52 | Log(table.toString());
53 | }
54 | } catch (err) { }
55 | }
56 |
57 | static formatMessage(message) {
58 | message = message.split(' ');
59 | message = message.map((word, i) => {
60 | if ((i + 1) % 7 === 0) return `${word}\n`;
61 | return `${word} `;
62 | }).map(word => colors.cyan(word));
63 | message = message.join('');
64 | return message;
65 | }
66 |
67 | }
68 |
69 | module.exports = AthomMessage;
70 |
--------------------------------------------------------------------------------
/bin/cmds/app/run.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const Log = require('../../../lib/Log');
4 | const App = require('../../../lib/App');
5 |
6 | exports.desc = 'Run a Homey App in development mode';
7 | exports.builder = yargs => {
8 | return yargs
9 | .option('clean', {
10 | alias: 'c',
11 | type: 'boolean',
12 | default: false,
13 | desc: 'Delete all userdata, paired devices etc. before running the app.',
14 | })
15 | .option('remote', {
16 | alias: 'r',
17 | type: 'boolean',
18 | default: false,
19 | desc: 'Upload the app to Homey Pro and run remotely, instead of a Docker container on this machine. Defaults to true for Homey Pro 2019 and earlier.',
20 | })
21 | .option('skip-build', {
22 | alias: 's',
23 | type: 'boolean',
24 | default: false,
25 | desc: 'Skip the automatic build step.',
26 | })
27 | .option('link-modules', {
28 | alias: 'l',
29 | type: 'string',
30 | default: '',
31 | desc: 'Provide a comma-separated path to local Node.js modules to link. Only works when running the app inside Docker.',
32 | })
33 | .option('network', {
34 | alias: 'n',
35 | default: 'bridge',
36 | type: 'string',
37 | description: 'Docker network mode. Must match name from `docker network ls`. Only works when running the app inside Docker.',
38 | })
39 | .option('docker-socket-path', {
40 | default: undefined,
41 | type: 'string',
42 | description: 'Path to the Docker socket.',
43 | });
44 | };
45 | exports.handler = async yargs => {
46 | try {
47 | const app = new App(yargs.path);
48 | await app.run({
49 | remote: yargs.remote,
50 | clean: yargs.clean,
51 | skipBuild: yargs.skipBuild,
52 | linkModules: yargs.linkModules,
53 | network: yargs.network,
54 | dockerSocketPath: yargs.dockerSocketPath,
55 | });
56 | } catch (err) {
57 | if (err instanceof Error && err.stack) {
58 | Log.error(err.stack);
59 | } else {
60 | Log.error(err);
61 | }
62 | process.exit(1);
63 | }
64 | };
65 |
--------------------------------------------------------------------------------
/lib/Settings.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const os = require('os');
4 | const fs = require('fs');
5 | const path = require('path');
6 | const util = require('util');
7 |
8 | const Log = require('./Log');
9 |
10 | const statAsync = util.promisify(fs.stat);
11 | const readFileAsync = util.promisify(fs.readFile);
12 | const writeFileAsync = util.promisify(fs.writeFile);
13 | const mkdirAsync = util.promisify(fs.mkdir);
14 |
15 | class Settings {
16 |
17 | constructor() {
18 | this._settings = null;
19 | this._settingsPath = this.getSettingsPath();
20 | }
21 |
22 | getSettingsDirectory() {
23 | if (process.env.HOMEY_HOME) {
24 | return process.env.HOMEY_HOME;
25 | }
26 |
27 | const platform = os.platform();
28 |
29 | if (platform === 'win32') {
30 | return path.join(process.env.APPDATA, 'athom-cli');
31 | }
32 |
33 | return path.join(process.env.HOME, '.athom-cli');
34 | }
35 |
36 | getSettingsPath() {
37 | return path.join(this.getSettingsDirectory(), 'settings.json');
38 | }
39 |
40 | async _getSettings() {
41 | if (this._settings) return this._settings;
42 |
43 | try {
44 | const data = await readFileAsync(this._settingsPath, 'utf8');
45 | const json = JSON.parse(data);
46 | this._settings = json;
47 | } catch (err) {
48 | if (err.code !== 'ENOENT') Log(err);
49 | this._settings = {};
50 | }
51 | return this._settings;
52 | }
53 |
54 | async get(key) {
55 | await this._getSettings();
56 | return this._settings[key] || null;
57 | }
58 |
59 | async set(key, value) {
60 | await this._getSettings();
61 |
62 | this._settings[key] = value;
63 |
64 | // create directory if not exists
65 | const dir = path.dirname(this._settingsPath);
66 | try {
67 | await statAsync(dir);
68 | } catch (err) {
69 | if (err.code !== 'ENOENT') throw err;
70 | await mkdirAsync(dir);
71 | }
72 |
73 | const json = JSON.stringify(this._settings, false, 4);
74 | await writeFileAsync(this._settingsPath, json);
75 |
76 | return this.get(key);
77 | }
78 |
79 | async unset(key) {
80 | return this.set(key, null);
81 | }
82 |
83 | }
84 |
85 | module.exports = Settings;
86 |
--------------------------------------------------------------------------------
/.github/workflows/update-homey-lib.yml:
--------------------------------------------------------------------------------
1 | name: Update homey-lib
2 |
3 | # About this workflow:
4 | # This workflow is triggered by a 'repository_dispatch' event, this event can be triggered using an API call or using
5 | # another GitHub Action workflow (see ./workflows/trigger-repository-dispatch-event.yml).
6 |
7 | # GitHub repo configuration:
8 | # 1. Go to Manage access and add 'Github Actions' team with role: admin.
9 |
10 | # Note: make sure to specify the 'types' property of the 'repository_dispatch' event to make sure this workflow is only
11 | # triggered by the expected 'repository_dispatch' event.
12 |
13 | on:
14 | repository_dispatch:
15 | types: "update-homey-lib" # Specify the event_type to listen to
16 |
17 | jobs:
18 | receive-repository-dispatch-event:
19 | runs-on: ubuntu-latest
20 | name: Create PR for homey-lib update
21 | steps:
22 |
23 | # Checks out the current repository.
24 | - name: Checkout git repository
25 | uses: actions/checkout@v2
26 | with:
27 | # The token below is only necessary if you want to push the version bump to a protected branch
28 | token: ${{ secrets.HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN }}
29 |
30 | # Set git config to reflect Homey Github Actions Bot user
31 | - name: Set up HomeyGithubActionsBot git user
32 | run: |
33 | git config --local user.email "sysadmin+githubactions@athom.com"
34 | git config --local user.name "Homey Github Actions Bot"
35 |
36 | # Configures a Node.js environment.
37 | - name: Set up node 12 environment
38 | uses: actions/setup-node@v1
39 | with:
40 | node-version: '16'
41 | # Needed for publishing to npm
42 | registry-url: 'https://registry.npmjs.org'
43 |
44 | - name: Bump homey-lib to latest
45 | run: |
46 | npm ci
47 | npm install homey-lib@latest
48 |
49 | - name: Commit homey-lib version bump
50 | run: |
51 | git add .
52 | git commit -m "chore: update homey-lib"
53 |
54 | - name: Create pull request
55 | uses: peter-evans/create-pull-request@v3
56 | with:
57 | title: "chore: update homey-lib"
58 | body: "Update homey-lib to the latest published version on NPM. This PR was automatically created by a homey-lib deployment."
59 | reviewers: "jeroenwienk"
60 | assignees: "jeroenwienk"
61 | branch: "bump/homey-lib"
62 | branch-suffix: "short-commit-hash"
63 |
--------------------------------------------------------------------------------
/lib/NpmCommands.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const util = require('util');
5 | const childProcess = require('child_process');
6 |
7 | const Log = require('./Log');
8 |
9 | const exec = util.promisify(childProcess.exec);
10 |
11 | class NpmCommands {
12 |
13 | /**
14 | * Execute npm install for a given packageId or array of packageIds.
15 | * @param {string[]} packages - List of packages that should be installed (e.g. ['request'] or ['request@1.2.3'])
16 | * @param {{ appPath?: string }} [options] - Current working directory where npm install should be executed.
17 | * @returns {Promise}
18 | */
19 | static async install(packages, { appPath } = {}) {
20 | Log.success(`Installing dependencies: ${packages.join(', ')}`);
21 | await exec(`npm install --save ${packages.join(' ')}`, { cwd: appPath });
22 | Log.success('Installation complete');
23 | }
24 |
25 | /**
26 | * Execute npm install for a given packageId or array of packageIds.
27 | * @param {string[]} packages - List of packages that should be installed (e.g. ['request'] or ['request@1.2.3'])
28 | * @param {{ appPath?: string }} [options] - Current working directory where npm install should be executed.
29 | * @returns {Promise}
30 | */
31 | static async installDev(packages, { appPath } = {}) {
32 | Log.success(`Installing dev dependencies: ${packages.join(', ')}`);
33 | await exec(`npm install --save-dev ${packages.join(' ')}`, { cwd: appPath });
34 | Log.success('Installation complete');
35 | }
36 |
37 | /**
38 | * Execute npm ls to get a list of production dependencies.
39 | * @param {{ appPath?: string }} [options]
40 | * @returns {Promise}
41 | */
42 | static async getProductionDependencies({ appPath } = {}) {
43 | // Note: on npm@6 this command lists packages from your package.json.
44 | // On npm@7 and above this list packages that are in your node_modules folder.
45 | // This means we can end up with "extra" packages that are still present in node_modules but not
46 | // listed in package.json or package-lock.json.
47 | // The --package-lock-only flag prevents this but then it will throw when there is no lock file.
48 | const { stdout } = await exec('npm ls --parseable --all --only=prod', { cwd: appPath });
49 |
50 | return stdout
51 | .split(/\r?\n/)
52 | .map(filePath => path.relative(appPath, filePath))
53 | .filter(filePath => filePath !== '');
54 | }
55 |
56 | }
57 |
58 | module.exports = NpmCommands;
59 |
--------------------------------------------------------------------------------
/assets/templates/app/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Athom and Homey
2 |
3 | First off all, thank you for taking the time to contribute!
4 |
5 | The following is a set of guidelines for contributing to Athom and its packages, which are hosted in the [Athom Organization](https://github.com/athombv) on GitHub. These are just guidelines, not rules. Use your best judgment, and feel free to contact us if you have any questions.
6 |
7 | Please join our [community slack](https://slack.athom.com), if you have not done so already.
8 | We also have a [community forum](https://community.homey.app) for general discussions.
9 |
10 |
11 | ## Before submitting a bug or feature request
12 |
13 | * **Have you actually read the error message**?
14 | * Have you searched for similar issues?
15 | * Have you updated homey, all apps, and the development tools (if applicable)?
16 | * Have you checked that it's not a problem with one of the apps you're using, rather than Homey itself?
17 | * Have you looked at what's involved in fixing/implementing this?
18 |
19 | Capable programmers should always attempt to investigate and fix problems themselves before asking for others to help. Submit a pull request instead of an issue!
20 |
21 | ## A great bug report contains
22 |
23 | * Context – what were you trying to achieve?
24 | * Detailed steps to reproduce the error from scratch. Try isolating the minimal amount of code needed to reproduce the error.
25 | * Any applicable log files or ID's.
26 | * Evidence you've looked into solving the problem and ideally, a theory on the cause and a possible solution.
27 |
28 | ## A great feature request contains
29 |
30 | * The current situation.
31 | * How and why the current situation is problematic.
32 | * A detailed proposal or pull request that demonstrates how the problem could be solved.
33 | * A use case – who needs this feature and why?
34 | * Any caveats.
35 |
36 | ## A great pull request contains
37 |
38 | * Minimal changes. Only submit code relevant to the current issue. Other changes should go in new pull requests.
39 | * Minimal commits. Please squash to a single commit before sending your pull request.
40 | * No conflicts. Please rebase off the latest master before submitting.
41 | * Code conforming to the existing conventions and formats. i.e. Please don't reformat whitespace.
42 | * Passing tests in the test folder (if applicable). Use existing tests as a reference.
43 | * Relevant documentation.
44 |
45 | ## Speeding up your pull request
46 | Merging pull requests takes time. While we always try to merge your pull request as soon as possible, there are certain things you can do to speed up this process.
47 |
48 | * Ask developers to review your code changes and post their feedback.
49 | * Ask users to test your changes and post their feedback.
50 | * Keep your changes to the minimal required amount, and dedicated to one issue/feature only.
--------------------------------------------------------------------------------
/assets/templates/app/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | education, socio-economic status, nationality, personal appearance, race,
10 | religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at support@athom.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
--------------------------------------------------------------------------------
/.github/workflows/publish-package-npm.yml:
--------------------------------------------------------------------------------
1 | name: Publish to NPM
2 |
3 | # Version: 2.1.0
4 | # Modified: No
5 | # Requirements:
6 | # - Ensure you've run `npm version major|minor|patch` on the `master` branch before merging to `production`.
7 | #
8 | # This GitHub Workflow:
9 | # 1. [Optional] If `npm run build` exists. If so, it runs `npm ci` and `npm run build`.
10 | # 2. Publishes the package to the NPM registry.
11 | #
12 | # Secrets:
13 | # - HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN
14 | # - NPM_AUTH_TOKEN: required for publishing to npm
15 | # - SLACK_WEBHOOK_URL: required for posting a message in #software
16 |
17 | # Note: when publishing a scoped npm package (e.g. @athombv/node-my-package),
18 | # add "publishConfig": { "access": "public" } to your package.json.
19 | on:
20 | push:
21 | branches:
22 | - testing
23 | - production
24 |
25 | jobs:
26 | publish:
27 | name: Publish
28 | runs-on: ubuntu-latest
29 | steps:
30 | - name: Checkout git repository
31 | uses: actions/checkout@v3
32 |
33 | # Setup
34 | - name: Set up node 16 environment
35 | uses: actions/setup-node@v3
36 | with:
37 | node-version: 16
38 | registry-url: 'https://npm.pkg.github.com'
39 |
40 | # Sets package.json name & version to environment.
41 | - name: Get Package Info
42 | run: |
43 | NAME="$(node -p "require('./package.json').name")"
44 | echo package_name=${NAME} >> $GITHUB_ENV
45 |
46 | VERSION="$(node -p "require('./package.json').version")"
47 | echo package_version=${VERSION} >> $GITHUB_ENV
48 |
49 | # Ensure `packake.json .files` exists.
50 | - name: Verify
51 | run: |
52 | if ! cat package.json | jq -e .files; then
53 | echo "Missing 'files' array in package.json."
54 | exit 1
55 | fi
56 |
57 | # Run `npm ci && npm run build` if it exists.
58 | - name: Build
59 | run: |
60 | if jq --exit-status '.scripts | has("build")' package.json; then
61 | echo "'npm run build' does exist. Building..."
62 | npm ci --ignore-scripts --audit=false
63 | npm run build
64 | else
65 | echo "'npm run build' does not exist. Skipping build..."
66 | fi
67 | env:
68 | NODE_AUTH_TOKEN: ${{ secrets.HOMEY_GITHUB_ACTIONS_BOT_PERSONAL_ACCESS_TOKEN }}
69 |
70 | # Configure NPM to use the NPM Registry
71 | - name: Configure NPM
72 | run: |
73 | npm config set registry https://registry.npmjs.org
74 | npm config set @athombv:registry https://registry.npmjs.org
75 | npm config set //registry.npmjs.org/:_authToken=${{ secrets.NPM_AUTH_TOKEN }} -q
76 |
77 | # Publish when this action is running on branch production.
78 | - name: Publish
79 | if: github.ref == 'refs/heads/production'
80 | run: |
81 | npm publish
82 |
83 | # Publish to beta when this action is running on branch testing.
84 | - name: Publish (beta)
85 | if: github.ref == 'refs/heads/testing'
86 | run: |
87 | npm publish --tag beta
88 |
89 | # Post a Slack notification on success/failure
90 | - name: Slack notify
91 | if: always()
92 | uses: innocarpe/actions-slack@v1
93 | with:
94 | status: ${{ job.status }}
95 | success_text: '${{github.repository}} - Published ${{ env.package_name }}@${{ env.package_version }} to npm 🚀'
96 | failure_text: '${{github.repository}} - Failed to publish ${{ env.package_name }}@${{ env.package_version }} to npm'
97 | env:
98 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
99 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
100 |
--------------------------------------------------------------------------------
/lib/GitCommands.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const util = require('util');
4 | const fs = require('fs');
5 | const _path = require('path');
6 | const childProcess = require('child_process');
7 |
8 | const exec = util.promisify(childProcess.exec);
9 | const statAsync = util.promisify(fs.stat);
10 |
11 | class GitCommands {
12 |
13 | constructor(appPath) {
14 | if (typeof appPath !== 'string') throw new Error('Expected path to execute git command in');
15 | this.path = appPath;
16 | }
17 |
18 | /**
19 | * Check if git is installed. By using --version git will not exit with an error code
20 | */
21 | static async isGitInstalled() {
22 | try {
23 | const { stdout } = await exec('git --version');
24 | return !!stdout;
25 | } catch (error) {
26 | return false;
27 | }
28 | }
29 |
30 | /**
31 | * Check if the cwd is contains a git repo.
32 | * @param {String} path
33 | * @returns Boolean whether or not .git has been detected.
34 | */
35 | static async isGitRepo({ path }) {
36 | try {
37 | await statAsync(_path.join(path, '.git'));
38 | return true;
39 | } catch (err) {
40 | return false;
41 | }
42 | }
43 |
44 | /**
45 | * Check if the repository contains uncommitted changes
46 | * @returns Boolean, true if there are uncommitted changes detected.
47 | */
48 | async hasUncommittedChanges() {
49 | const result = await this._executeGitCommand('status');
50 | return typeof result === 'string' && (result.includes('not staged') || result.includes('untracked'));
51 | }
52 |
53 | /**
54 | * Create a git tag with the given version number and optional message.
55 | * @param{Object<{version, message}>} Version: Used for the tag name,
56 | * message: The message to describe the tag.
57 | * @returns Git output or error when the command failed.
58 | */
59 | async createTag({ version, message }) {
60 | if (typeof version === 'string' && typeof message === 'string') {
61 | if (!version || version === '') {
62 | throw new Error('✖ A version is required to create a tag.');
63 | }
64 | if (await this.hasUncommittedChanges()) {
65 | throw new Error('✖ Please commit your changes to Git first.');
66 | }
67 |
68 | const result = await this._executeGitCommand(`tag -a "v${version}" -m "${message}"`);
69 |
70 | if (typeof result.stderr === 'string' && result.stderr.includes('already')) {
71 | throw new Error('✖ This Git tag already exists!');
72 | }
73 | } else {
74 | throw new Error('Invalid type received');
75 | }
76 | }
77 |
78 | /**
79 | * Method that pushes a newly created tag (version) to the remote.
80 | * @param {String} version
81 | * @returns {Promise}
82 | */
83 | async pushTag({ version }) {
84 | if (typeof version !== 'string') throw new Error('Invalid type received');
85 | return this._executeGitCommand(`push origin v${version}`);
86 | }
87 |
88 | /**
89 | * Obtain all the tags from the given repository.
90 | * @returns Array with git tags.
91 | * */
92 | async getTags() {
93 | const output = await this._executeGitCommand('tag -l');
94 |
95 | // Create an array based on line breaks, then filter any empty String out of it.
96 | return output.split(/\r\n|\r|\n/).filter(value => {
97 | return Boolean(value);
98 | });
99 | }
100 |
101 | /**
102 | * Deletes a tag from the given repository.
103 | * @param version version string to delete
104 | * @returns Output from @_executeGitCommand
105 | */
106 | async deleteTag(version) {
107 | if (typeof version === 'string') return this._executeGitCommand(`tag -d ${version}`);
108 | return new Error('Invalid type received');
109 | }
110 |
111 | /**
112 | * Commit a given file.
113 | * @param {Object<{file, message, description}>} File:
114 | * the file to commit, message: Commit message, description: Commit description
115 | * @returns Output from @_executeGitCommand
116 | */
117 | async commitFile({ file, message, description }) {
118 | if (typeof file !== 'string' || typeof message !== 'string') throw new Error('Invalid file or message type received');
119 | return this.commitFiles({ files: [file], message, description });
120 | }
121 |
122 | /**
123 | * Commit an Array of files.
124 | * @param {Object<{files, message, description}>} Files:
125 | * array of files to commit, message: Commit message, description: Commit description
126 | * @returns Output from @_executeGitCommand
127 | */
128 | async commitFiles({ files, message, description }) {
129 | if (files instanceof Array && typeof message === 'string') {
130 | await this._executeGitCommand(`add ${files.join(' ')}`); // Make sure untracked files are added first
131 | return this._executeGitCommand(`commit -o ${files.join(' ')} -m "${message}" ${typeof description === 'string' ? `-m "${description}"` : ''}`);
132 | }
133 | return new Error('Invalid type received');
134 | }
135 |
136 | /**
137 | * Method that checks if a remote origin is present.
138 | * @returns {Promise}
139 | */
140 | async hasRemoteOrigin() {
141 | try {
142 | await this._executeGitCommand('config --get remote.origin.url');
143 | return true;
144 | } catch (error) {
145 | return false;
146 | }
147 | }
148 |
149 | /**
150 | * Method that checks if a remote origin is present
151 | * and if so pushes currently staged changes to that remote.
152 | * @returns {Promise<>}
153 | */
154 | async push() {
155 | if (!await this.hasRemoteOrigin()) throw new Error('✖ Cannot push to remote: `remote "origin"` not found in Git config.');
156 | return this._executeGitCommand('push');
157 | }
158 |
159 | /**
160 | * Function to execute git commands.
161 | * @param command: Git command to execute, eg commit, tag, push etc.
162 | * @returns Git command output or error when command failed.
163 | */
164 | async _executeGitCommand(command) {
165 | if (typeof this.path !== 'string') throw new Error('Expected path to execute git command in');
166 | if (!await GitCommands.isGitInstalled()) throw new Error('Git is not installed');
167 |
168 | const { stdout } = await exec(`git ${command}`, { cwd: this.path });
169 | return stdout;
170 | }
171 |
172 | }
173 |
174 | module.exports = GitCommands;
175 |
--------------------------------------------------------------------------------
/lib/AthomApi.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const os = require('os');
5 |
6 | const inquirer = require('inquirer');
7 | const colors = require('colors');
8 | const _ = require('underscore');
9 | const fetch = require('node-fetch');
10 | const express = require('express');
11 | const open = require('open');
12 | const {
13 | AthomCloudAPI,
14 | HomeyAPI,
15 | APIErrorHomeyOffline,
16 | } = require('homey-api');
17 | const AthomCloudAPIToken = require('homey-api/lib/AthomCloudAPI/Token');
18 |
19 | const AthomApiStorage = require('./AthomApiStorage');
20 | const Log = require('./Log');
21 | const Settings = require('../services/Settings');
22 | const {
23 | ATHOM_API_CLIENT_ID,
24 | ATHOM_API_CLIENT_SECRET,
25 | ATHOM_API_LOGIN_URL,
26 | } = require('../config');
27 |
28 | class AthomApi {
29 |
30 | constructor() {
31 | this._api = null;
32 | this._user = null;
33 | this._homeys = null;
34 | this._activeHomey = null;
35 | }
36 |
37 | _createApi() {
38 | this._store = new AthomApiStorage();
39 | this._api = new AthomCloudAPI({
40 | clientId: ATHOM_API_CLIENT_ID,
41 | clientSecret: ATHOM_API_CLIENT_SECRET,
42 | store: this._store,
43 |
44 | // Authenticate with Personal Access Token (PAT) if provided
45 | ...(process.env.HOMEY_PAT
46 | ? {
47 | autoRefreshTokens: false,
48 | token: new AthomCloudAPIToken({
49 | access_token: process.env.HOMEY_PAT,
50 | }),
51 | }
52 | : {}),
53 | });
54 | }
55 |
56 | async _initApi() {
57 | if (this._api) return this._api;
58 |
59 | this._createApi();
60 |
61 | // Migration from node-athom-api to node-homey-api
62 | const athomApiState = await Settings.get('_athom_api_state');
63 | if (athomApiState && athomApiState.athomCloudToken) {
64 | await Settings.set('homeyApi', {
65 | token: {
66 | token_type: 'bearer',
67 | access_token: athomApiState.athomCloudToken.access_token,
68 | refresh_token: athomApiState.athomCloudToken.refresh_token,
69 | expires_in: 3660,
70 | grant_type: 'authorization_code',
71 | },
72 | });
73 | await Settings.unset('_athom_api_state');
74 | }
75 |
76 | // Ensure the user is logged in
77 | if (!await this._api.isLoggedIn()) {
78 | await this.login();
79 | }
80 |
81 | return this._api;
82 | }
83 |
84 | async login() {
85 | Log.success('Logging in...');
86 | let listener;
87 |
88 | this._createApi();
89 |
90 | const app = express();
91 | const port = await new Promise(resolve => {
92 | listener = app.listen(() => {
93 | resolve(listener.address().port);
94 | });
95 | });
96 |
97 | const url = `${ATHOM_API_LOGIN_URL}?port=${port}&clientId=${ATHOM_API_CLIENT_ID}`;
98 | Log(colors.bold('To log in with your Athom Account, please visit', colors.underline.cyan(url)));
99 | open(url).catch(err => { });
100 |
101 | const code = await Promise.race([
102 |
103 | // Input code automatically by webserver
104 | Promise.resolve().then(async () => {
105 | const codePromise = new Promise(resolve => {
106 | app.get('/auth', (req, res) => {
107 | res.sendFile(path.join(__dirname, '..', 'assets', '1px.png'));
108 | if (req.query.code) {
109 | Log(req.query.code);
110 | resolve(req.query.code);
111 | }
112 | });
113 | });
114 | return codePromise;
115 | }),
116 |
117 | // Input code manually
118 | inquirer.prompt([
119 | {
120 | type: 'text',
121 | name: 'receivedCode',
122 | message: 'Paste the code:',
123 | },
124 | ]).then(({ receivedCode }) => {
125 | if (!receivedCode) {
126 | throw new Error('Invalid code!');
127 | }
128 | return receivedCode;
129 | }),
130 |
131 | new Promise((resolve, reject) => {
132 | setTimeout(() => {
133 | Log('');
134 | reject(new Error('Timeout getting authorization code!'));
135 | }, 1000 * 60 * 5); // 5 minutes
136 | }),
137 | ]);
138 |
139 | listener.close();
140 |
141 | await this._api.authenticateWithAuthorizationCode({ code });
142 |
143 | try {
144 | const profile = await this.getProfile();
145 |
146 | Log.success(`You are now logged in as ${profile.firstname} ${profile.lastname} <${profile.email}>`);
147 | } catch (err) {
148 | Log.error(`Invalid Account Token, please try again:${err.stack}`);
149 | }
150 | }
151 |
152 | async logout() {
153 | Log.success('You are now logged out');
154 | await this._createApi();
155 | await this._api.logout();
156 | await this.unsetActiveHomey();
157 | }
158 |
159 | async getProfile() {
160 | await this._initApi();
161 | return this._api.getAuthenticatedUser();
162 | }
163 |
164 | async getHomey(homeyId) {
165 | const homeys = await this.getHomeys();
166 | for (let i = 0; i < homeys.length; i++) {
167 | const homey = homeys[i];
168 | if (homey.id === homeyId) return homey;
169 | }
170 | throw new Error(`Homey Not Found: ${homeyId}`);
171 | }
172 |
173 | async getHomeys({
174 | cache = true,
175 | local = true,
176 | } = {}) {
177 | if (cache && this._homeys) return this._homeys;
178 |
179 | await this._initApi();
180 |
181 | this._user = this._user || await this.getProfile();
182 | this._homeys = await this._user.getHomeys();
183 |
184 | // find USB connected Homeys
185 | if (local) {
186 | const ifaces = os.networkInterfaces();
187 |
188 | for (const adapters of Object.values(ifaces)) {
189 | for (const adapter of Object.values(adapters)) {
190 | try {
191 | let ip = adapter.address.split('.');
192 | if (ip[0] !== '10') continue;
193 | ip[3] = '1';
194 | ip = ip.join('.');
195 |
196 | const res = await fetch(`http://${ip}/api/manager/webserver/ping`, {
197 | timeout: 1000,
198 | });
199 |
200 | const homeyId = res.headers.get('x-homey-id');
201 | if (!homeyId) continue;
202 |
203 | const homey = _.findWhere(this._homeys, { id: homeyId });
204 | if (homey) {
205 | homey.usb = ip;
206 | }
207 | } catch (err) { }
208 | }
209 | }
210 | }
211 |
212 | return this._homeys;
213 | }
214 |
215 | async getActiveHomey() {
216 | if (!this._activeHomey) {
217 | let activeHomey = await Settings.get('activeHomey');
218 | if (activeHomey === null) {
219 | activeHomey = await this.selectActiveHomey();
220 | }
221 |
222 | const homey = await this.getHomey(activeHomey.id);
223 | const homeyApi = await homey.authenticate({
224 | strategy: homey.platform === HomeyAPI.PLATFORMS.CLOUD
225 | ? [
226 | HomeyAPI.DISCOVERY_STRATEGIES.CLOUD,
227 | ]
228 | : [
229 | HomeyAPI.DISCOVERY_STRATEGIES.LOCAL,
230 | HomeyAPI.DISCOVERY_STRATEGIES.LOCAL_SECURE,
231 | HomeyAPI.DISCOVERY_STRATEGIES.REMOTE_FORWARDED,
232 | ],
233 | }).catch(err => {
234 | if (err instanceof APIErrorHomeyOffline) {
235 | throw new Error(`${homey.name} (${homey.id}) seems to be offline. Are you sure you're in the same LAN network?`);
236 | }
237 | throw err;
238 | });
239 |
240 | if (homey.usb) {
241 | homeyApi.__baseUrlPromise = Promise.resolve(`http://${homey.usb}:80`);
242 | }
243 |
244 | // Required when creating SDK client in App.js
245 | homeyApi.model = homey.model;
246 |
247 | this._activeHomey = homeyApi;
248 | }
249 |
250 | return this._activeHomey;
251 | }
252 |
253 | async setActiveHomey({ id, name }) {
254 | return Settings.set('activeHomey', { id, name });
255 | }
256 |
257 | async unsetActiveHomey() {
258 | return Settings.unset('activeHomey');
259 | }
260 |
261 | async selectActiveHomey({
262 | id,
263 | name,
264 | filter = {
265 | online: true,
266 | local: true,
267 | },
268 | } = {}) {
269 | const homeys = await this.getHomeys();
270 | let activeHomey;
271 |
272 | if (typeof id === 'string') {
273 | activeHomey = _.findWhere(homeys, { _id: id });
274 | } else if (typeof name === 'string') {
275 | activeHomey = _.findWhere(homeys, { name });
276 | } else {
277 | const answers = await inquirer.prompt([
278 | {
279 | type: 'list',
280 | name: 'homey',
281 | message: 'Choose an active Homey:',
282 | choices: homeys
283 | .filter(homey => {
284 | if (filter.online && homey.state && homey.state.indexOf('online') !== 0) return false;
285 | return true;
286 | })
287 | .map(homey => ({
288 | value: {
289 | name: homey.name,
290 | id: homey.id,
291 | },
292 | name: homey.name,
293 | })),
294 | },
295 | ]);
296 |
297 | activeHomey = answers.homey;
298 | }
299 |
300 | if (!activeHomey) {
301 | throw new Error('No Homey found');
302 | }
303 |
304 | const result = await this.setActiveHomey(activeHomey);
305 |
306 | Log(`You have selected \`${activeHomey.name}\` as your active Homey.`);
307 |
308 | return result;
309 | }
310 |
311 | async unselectActiveHomey() {
312 | await this.unsetActiveHomey();
313 | Log('You have unselected your active Homey.');
314 | }
315 |
316 | async createDelegationToken(opts) {
317 | await this._initApi();
318 | return this._api.createDelegationToken(opts);
319 | }
320 |
321 | }
322 |
323 | module.exports = AthomApi;
324 |
--------------------------------------------------------------------------------
/lib/ZWave.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const https = require('https');
4 | const colors = require('colors');
5 | const inquirer = require('inquirer');
6 | const fetch = require('node-fetch');
7 | const Log = require('./Log');
8 |
9 | class ZWave {
10 |
11 | static async autocompleteDriver() {
12 | const zwaveJson = {};
13 | const settingsJson = [];
14 |
15 | if (true) {
16 | // The z-wavealliance.org API is currently unreliable, ask all properties from the user.
17 | const { manufacturerId } = await inquirer.prompt([
18 | {
19 | type: 'input',
20 | name: 'manufacturerId',
21 | message: 'What is the Manufacturer ID (in decimal)?',
22 | },
23 | ]);
24 |
25 | if (!manufacturerId) {
26 | throw new Error('Manufacturer ID is required');
27 | }
28 |
29 | zwaveJson.manufacturerId = parseInt(manufacturerId, 10);
30 |
31 | const { productTypeId } = await inquirer.prompt([
32 | {
33 | type: 'input',
34 | name: 'productTypeId',
35 | message: 'What is the Product Type ID (in decimal)? If multiple, separate by comma.',
36 | },
37 | ]);
38 |
39 | if (!productTypeId) {
40 | throw new Error('Product Type ID is required');
41 | }
42 |
43 | zwaveJson.productTypeId = productTypeId.split(',').map(id => parseInt(id.trim(), 10));
44 |
45 | const { productId } = await inquirer.prompt([
46 | {
47 | type: 'input',
48 | name: 'productId',
49 | message: 'What is the Product ID (in decimal)? If multiple, separate by comma.',
50 | },
51 | ]);
52 |
53 | if (!productId) {
54 | throw new Error('Product ID is required');
55 | }
56 |
57 | zwaveJson.productId = productId.split(',').map(id => parseInt(id.trim(), 10));
58 |
59 | const { sigmaAllianceProductId } = await inquirer.prompt([
60 | {
61 | type: 'input',
62 | name: 'sigmaAllianceProductId',
63 | message: 'What is the Z-Wave Alliance Product ID? Leave empty if unknown.',
64 | },
65 | ]);
66 |
67 | if (sigmaAllianceProductId) {
68 | zwaveJson.zwaveAllianceProductId = sigmaAllianceProductId;
69 | }
70 |
71 | const { sigmaAllianceProductDocumentation } = await inquirer.prompt([
72 | {
73 | type: 'input',
74 | name: 'sigmaAllianceProductDocumentation',
75 | message: 'What is the Z-Wave Alliance Product Documentation URL? Leave empty if unknown.',
76 | },
77 | ]);
78 |
79 | if (sigmaAllianceProductDocumentation) {
80 | zwaveJson.zwaveAllianceProductDocumentation = sigmaAllianceProductDocumentation;
81 | }
82 |
83 | const { inclusionDescription } = await inquirer.prompt([
84 | {
85 | type: 'input',
86 | name: 'inclusionDescription',
87 | message: 'Enter a short description on how to enable inclusion mode. Leave empty if unknown.',
88 | },
89 | ]);
90 |
91 | if (inclusionDescription) {
92 | zwaveJson.learnmode = {
93 | instruction: {
94 | en: inclusionDescription,
95 | },
96 | };
97 | }
98 |
99 | const { exclusionDescription } = await inquirer.prompt([
100 | {
101 | type: 'input',
102 | name: 'exclusionDescription',
103 | message: 'Enter a short description on how to enable exclusion mode. Leave empty if unknown.',
104 | },
105 | ]);
106 |
107 | if (exclusionDescription) {
108 | zwaveJson.unlearnmode = {
109 | instruction: {
110 | en: exclusionDescription,
111 | },
112 | };
113 | }
114 |
115 | Log.success(`See the developer documentation at ${colors.underline('https://apps.developer.homey.app/wireless/z-wave')} on how to configure associationGroups and device settings.`);
116 |
117 | return { zwave: zwaveJson, settings: settingsJson };
118 | }
119 |
120 | const { hasSigmaId } = await inquirer.prompt([
121 | {
122 | type: 'confirm',
123 | name: 'hasSigmaId',
124 | message: `Do you have a Z-Wave Alliance ID? This ID is four digits, found in the URL at ${colors.underline('https://products.z-wavealliance.org/')}`,
125 | },
126 | ]);
127 |
128 | if (!hasSigmaId) return;
129 |
130 | const { sigmaId } = await inquirer.prompt([
131 | {
132 | type: 'input',
133 | name: 'sigmaId',
134 | message: 'What is the Z-Wave Alliance ID?',
135 | },
136 | ]);
137 |
138 | if (!sigmaId) return;
139 |
140 | const sigmaJson = await ZWave.getSigmaDetails(sigmaId);
141 |
142 | // set properties
143 | zwaveJson.manufacturerId = parseInt(sigmaJson.ManufacturerId, 10);
144 | zwaveJson.productTypeId = [parseInt(sigmaJson.ProductTypeId, 10)];
145 | zwaveJson.productId = [parseInt(sigmaJson.ProductId, 10)];
146 | zwaveJson.zwaveAllianceProductId = sigmaJson.Id;
147 | zwaveJson.zwaveAllianceProductDocumentation = sigmaJson.ManualUrl;
148 |
149 | // inclusion & exclusion
150 | if (sigmaJson.InclusionDescription) {
151 | zwaveJson.learnmode = {
152 | instruction: {
153 | en: sigmaJson.InclusionDescription,
154 | },
155 | };
156 | }
157 |
158 | if (sigmaJson.ExclusionDescription) {
159 | zwaveJson.unlearnmode = {
160 | instruction: {
161 | en: sigmaJson.ExclusionDescription,
162 | },
163 | };
164 | }
165 |
166 | // get associationGroups and associationGroupsOptions if defined
167 | if (Array.isArray(sigmaJson.AssociationGroups)) {
168 | sigmaJson.AssociationGroups.forEach(associationGroup => {
169 | let associationGroupNumber;
170 | try {
171 | associationGroupNumber = parseInt(associationGroup.GroupNumber, 2);
172 | } catch (err) {
173 | return;
174 | }
175 |
176 | if (Number.isNaN(associationGroupNumber)) return;
177 |
178 | zwaveJson.associationGroups = zwaveJson.associationGroups || [];
179 | zwaveJson.associationGroups.push(associationGroupNumber);
180 |
181 | if (associationGroup.Description) {
182 | zwaveJson.associationGroupsOptions = zwaveJson.associationGroupsOptions || {};
183 | zwaveJson.associationGroupsOptions[associationGroup.GroupNumber] = {
184 | hint: {
185 | en: associationGroup.Description,
186 | },
187 | };
188 | }
189 | });
190 | }
191 |
192 | // parse settings
193 | if (Array.isArray(sigmaJson.ConfigurationParameters)) {
194 | sigmaJson.ConfigurationParameters.forEach(configurationParameter => {
195 | const settingObj = {};
196 | settingObj.id = String(configurationParameter.ParameterNumber);
197 | settingObj.value = configurationParameter.DefaultValue;
198 | settingObj.label = {
199 | en: String(configurationParameter.Name),
200 | };
201 | settingObj.hint = {
202 | en: String(configurationParameter.Description),
203 | };
204 |
205 | settingObj.zwave = {
206 | index: configurationParameter.ParameterNumber,
207 | size: configurationParameter.Size,
208 | };
209 |
210 | // guess type
211 | if (configurationParameter.ConfigurationParameterValues
212 | && Array.isArray(configurationParameter.ConfigurationParameterValues)
213 | && configurationParameter.ConfigurationParameterValues.length === 2
214 | && (parseInt(configurationParameter.ConfigurationParameterValues[0].From, 10) === 0
215 | || parseInt(configurationParameter.ConfigurationParameterValues[0].From, 10) === 1)
216 | && (parseInt(configurationParameter.ConfigurationParameterValues[0].To, 10) === 0
217 | || parseInt(configurationParameter.ConfigurationParameterValues[0].To, 10) === 1)
218 | && (parseInt(configurationParameter.ConfigurationParameterValues[0].From, 10) === 0
219 | || parseInt(configurationParameter.ConfigurationParameterValues[0].From, 10) === 1)
220 | && (parseInt(configurationParameter.ConfigurationParameterValues[0].To, 10) === 0
221 | || parseInt(configurationParameter.ConfigurationParameterValues[0].To, 10) === 1)
222 | ) {
223 | settingObj.type = 'checkbox';
224 |
225 | if (settingObj.value === 0) {
226 | settingObj.value = false;
227 | } else {
228 | settingObj.value = true;
229 | }
230 | } else if (configurationParameter.ConfigurationParameterValues
231 | && Array.isArray(configurationParameter.ConfigurationParameterValues)
232 | && configurationParameter.ConfigurationParameterValues.length >= 3) {
233 | // Probably dropdown
234 | const dropdownOptions = [];
235 | configurationParameter.ConfigurationParameterValues.forEach(setting => {
236 | dropdownOptions.push({
237 | id: setting.From.toString() || setting.To.toString(),
238 | label: {
239 | en: setting.Description,
240 | },
241 | });
242 | });
243 | settingObj.values = dropdownOptions;
244 | settingObj.type = 'dropdown';
245 | settingObj.value = settingObj.value.toString();
246 | } else {
247 | settingObj.attr = {};
248 |
249 | const configVal = configurationParameter.ConfigurationParameterValues[0];
250 | if (Object.prototype.hasOwnProperty.call(configVal, 'From')) {
251 | settingObj.attr.min = parseInt(configVal.From, 10);
252 | }
253 |
254 | if (Object.prototype.hasOwnProperty.call(configVal, 'To')) {
255 | settingObj.attr.max = parseInt(configVal.To, 10);
256 | }
257 |
258 | // Determine if values are signed or not: https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
259 | // size is one, and max is larger than 127 -> unsigned
260 | if ((configurationParameter.Size === 1
261 | && settingObj.attr.max > 127
262 | && settingObj.attr.max < 255)
263 | || (configurationParameter.Size === 2
264 | && settingObj.attr.max > 32767
265 | && settingObj.attr.max < 65535)
266 | || (configurationParameter.Size === 4
267 | && settingObj.attr.max > 2147483647
268 | && settingObj.attr.max < 4294967295)) {
269 | settingObj.signed = false;
270 | }
271 |
272 | settingObj.type = 'number';
273 | }
274 |
275 | settingsJson.push(settingObj);
276 | });
277 | }
278 |
279 | return { zwave: zwaveJson, settings: settingsJson };
280 | }
281 |
282 | static async getSigmaDetails(sigmaId) {
283 | const agent = new https.Agent({
284 | rejectUnauthorized: false,
285 | });
286 |
287 | try {
288 | const response = await fetch(`https://products.z-wavealliance.org/Products/${sigmaId}/JSON`, { agent });
289 | if (!response.ok) throw new Error(response.statusText);
290 | const json = await response.json();
291 | return json;
292 | } catch (err) {
293 | throw new Error('Invalid Sigma Product ID');
294 | }
295 | }
296 |
297 | }
298 |
299 | module.exports = ZWave;
300 |
--------------------------------------------------------------------------------
/assets/templates/app/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/lib/HomeyCompose.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /*
4 | Homey Compose generates an app.json file based on scattered files,
5 | to make it easier to create apps with lots of functionality.
6 |
7 | It finds the following files:
8 | /.homeycompose/app.json
9 | /.homeycompose/capabilities/.json
10 | /.homeycompose/screensavers/.json
11 | /.homeycompose/signals/<433|868|ir>/.json
12 | /.homeycompose/flow//.json
13 | /.homeycompose/capabilities/.json
14 | /.homeycompose/discovery/.json
15 | /.homeycompose/drivers/templates/.json
16 | /.homeycompose/drivers/settings/.json
17 | /.homeycompose/drivers/flow//.json
18 | (flow card object, id and device arg is added automatically)
19 | /drivers//driver.compose.json (extend with "$extends": [ "" ])
20 | /drivers//driver.settings.compose.json
21 | (array with driver settings, extend with "$extends": ""))
22 | /drivers//driver.flow.compose.json (object with flow cards, device arg is added automatically)
23 | /drivers//driver.pair.compose.json (object with pair views)
24 | /drivers//driver.repair.compose.json (object with repair views)
25 | /.homeycompose/locales/en.json
26 | /.homeycompose/locales/en.foo.json
27 | */
28 |
29 | const fs = require('fs');
30 | const path = require('path');
31 | const util = require('util');
32 | const url = require('url');
33 |
34 | const fse = require('fs-extra');
35 | const _ = require('underscore');
36 | const deepmerge = require('deepmerge');
37 | const objectPath = require('object-path');
38 | const HomeyLib = require('homey-lib');
39 |
40 | const Log = require('./Log');
41 |
42 | const readFileAsync = util.promisify(fs.readFile);
43 | const writeFileAsync = util.promisify(fs.writeFile);
44 | const readdirAsync = util.promisify(fs.readdir);
45 |
46 | const deepClone = object => JSON.parse(JSON.stringify(object));
47 |
48 | const FLOW_TYPES = ['triggers', 'conditions', 'actions'];
49 |
50 | class HomeyCompose {
51 |
52 | // Temporary simpler api
53 | static async build({ appPath, usesModules }) {
54 | const compose = new HomeyCompose(appPath, usesModules);
55 | await compose.run();
56 | }
57 |
58 | constructor(appPath, usesModules) {
59 | this._appPath = appPath;
60 | this._usesModules = usesModules;
61 | }
62 |
63 | async run() {
64 | this._appPathCompose = path.join(this._appPath, '.homeycompose');
65 |
66 | this._appJsonPath = path.join(this._appPath, 'app.json');
67 | this._appJson = await this._getJsonFile(this._appJsonPath);
68 |
69 | this._appJsonPathCompose = path.join(this._appPathCompose, 'app.json');
70 | try {
71 | const appJSON = await this._getJsonFile(this._appJsonPathCompose);
72 | this._appJson = {
73 | _comment: 'This file is generated. Please edit .homeycompose/app.json instead.',
74 | ...appJSON,
75 | };
76 | } catch (err) {
77 | if (err.code !== 'ENOENT') throw new Error(err);
78 | }
79 |
80 | if (this._usesModules) {
81 | this._appJson.esm = true;
82 | }
83 |
84 | await this._composeFlow();
85 | await this._composeDrivers();
86 | await this._composeWidgets();
87 | await this._composeCapabilities();
88 | await this._composeDiscovery();
89 | await this._composeSignals();
90 | await this._composeScreensavers();
91 | await this._composeLocales();
92 | await this._saveAppJson();
93 | }
94 |
95 | extendSetting(settingsTemplates, settingObj) {
96 | if (settingObj.type === 'group') {
97 | for (const childSettingId of Object.keys(settingObj.children)) {
98 | this.extendSetting(settingsTemplates, settingObj.children[childSettingId]);
99 | }
100 | } else if (settingObj.$extends) {
101 | const templateIds = [].concat(settingObj.$extends);
102 |
103 | let settingTemplate = {};
104 | let templateId;
105 | for (const i of Object.keys(templateIds)) {
106 | templateId = templateIds[i];
107 |
108 | if (!Object.prototype.hasOwnProperty.call(settingsTemplates, templateId)) {
109 | throw new Error(`Invalid driver setting template for driver: ${templateId}`);
110 | }
111 | settingTemplate = Object.assign(settingTemplate, settingsTemplates[templateId]);
112 | }
113 |
114 | Object.assign(settingObj, {
115 | id: settingObj.$id || templateId,
116 | // We need to deep clone the settings template to make sure
117 | // replaceSpecialPropertiesRecursive doesn't mutate references
118 | // shared by multiple extended settings
119 | ...deepClone(settingTemplate),
120 | ...settingObj,
121 | });
122 | }
123 | }
124 |
125 | /*
126 | Find drivers in /drivers/:id/driver.compose.json
127 | */
128 | async _composeDrivers() {
129 | delete this._appJson.drivers;
130 |
131 | // use _getChildFolders to prevent any library or documentation files
132 | // ending up in the driver list.
133 | const drivers = await this._getChildFolders(path.join(this._appPath, 'drivers'));
134 |
135 | drivers.sort();
136 | for (let driverIndex = 0; driverIndex < drivers.length; driverIndex++) {
137 | const driverId = drivers[driverIndex];
138 | if (driverId.indexOf('.') === 0) continue;
139 |
140 | // merge json
141 | let driverJson = await this._getJsonFile(
142 | path.join(this._appPath, 'drivers', driverId, 'driver.compose.json'),
143 | );
144 | if (driverJson.$extends) {
145 | if (!Array.isArray(driverJson.$extends)) {
146 | driverJson.$extends = [driverJson.$extends];
147 | }
148 |
149 | const templates = await this._getJsonFiles(
150 | path.join(this._appPathCompose, 'drivers', 'templates'),
151 | );
152 | let templateJson = {};
153 |
154 | for (let j = 0; j < driverJson.$extends.length; j++) {
155 | const templateId = driverJson.$extends[j];
156 | templateJson = {
157 | ...templateJson,
158 | ...templates[templateId],
159 | };
160 | }
161 |
162 | driverJson = {
163 | ...templateJson,
164 | ...driverJson,
165 | };
166 | }
167 |
168 | driverJson.id = driverId;
169 |
170 | // merge settings
171 | try {
172 | driverJson.settings = await this._getJsonFile(
173 | path.join(this._appPath, 'drivers', driverId, 'driver.settings.compose.json'),
174 | );
175 | } catch (err) {
176 | if (err.code !== 'ENOENT') throw new Error(err);
177 | }
178 |
179 | // merge template settings
180 | try {
181 | const settingsTemplates = await this._getJsonFiles(
182 | path.join(this._appPathCompose, 'drivers', 'settings'),
183 | );
184 | if (Array.isArray(driverJson.settings)) {
185 | Object.values(driverJson.settings).forEach(setting => {
186 | this.extendSetting(settingsTemplates, setting);
187 | });
188 | }
189 | } catch (err) {
190 | if (err.code !== 'ENOENT') throw new Error(err);
191 | }
192 |
193 | // merge pair
194 | try {
195 | driverJson.pair = await this._getJsonFile(path.join(this._appPath, 'drivers', driverId, 'driver.pair.compose.json'));
196 | } catch (err) {
197 | if (err.code !== 'ENOENT') throw new Error(err);
198 | }
199 |
200 | if (Array.isArray(driverJson.pair)) {
201 | const appPairPath = path.join(this._appPath, 'drivers', driverId, 'pair');
202 | const composePairPath = path.join(this._appPathCompose, 'drivers', 'pair');
203 | let composePairViews = await this._getFiles(composePairPath);
204 | composePairViews = composePairViews.filter(view => {
205 | return view.indexOf('.') !== 0;
206 | });
207 |
208 | for (let j = 0; j < driverJson.pair.length; j++) {
209 | const driverPairView = driverJson.pair[j];
210 |
211 | if (driverPairView.$template) {
212 | const viewId = driverPairView.id;
213 | const templateId = driverPairView.$template;
214 | if (!composePairViews.includes(templateId)) {
215 | throw new Error(`Invalid pair template for driver ${driverId}: ${templateId}`);
216 | }
217 | if (!viewId || typeof viewId !== 'string') {
218 | throw new Error(
219 | `Invalid pair template "id" property for driver ${driverId}: ${templateId}`,
220 | );
221 | }
222 |
223 | await fse.ensureDir(appPairPath);
224 |
225 | // copy html
226 | let html = await readFileAsync(path.join(composePairPath, templateId, 'index.html'));
227 | html = html.toString();
228 | html = html.replace(/{{assets}}/g, `${viewId}.assets`);
229 | await writeFileAsync(path.join(appPairPath, `${viewId}.html`), html);
230 |
231 | // copy assets
232 | const composePairAssetsPath = path.join(composePairPath, templateId, 'assets');
233 | if (await fse.exists(composePairAssetsPath)) {
234 | await fse.copy(composePairAssetsPath, path.join(appPairPath, `${viewId}.assets`));
235 | }
236 | }
237 |
238 | // set pair options
239 | if (driverJson.$pairOptions) {
240 | for (const [id, options] of Object.entries(driverJson.$pairOptions)) {
241 | const view = _.findWhere(driverJson.pair, { id });
242 | if (view) {
243 | view.options = view.options || {};
244 | Object.assign(view.options, options);
245 | }
246 | }
247 | }
248 | }
249 | }
250 |
251 | // merge repair
252 | try {
253 | driverJson.repair = await this._getJsonFile(path.join(this._appPath, 'drivers', driverId, 'driver.repair.compose.json'));
254 | } catch (err) {
255 | if (err.code !== 'ENOENT') throw new Error(err);
256 | }
257 |
258 | if (Array.isArray(driverJson.repair)) {
259 | const appRepairPath = path.join(this._appPath, 'drivers', driverId, 'repair');
260 | const composeRepairPath = path.join(this._appPathCompose, 'drivers', 'repair');
261 | let composeRepairViews = await this._getFiles(composeRepairPath);
262 | composeRepairViews = composeRepairViews.filter(view => {
263 | return view.indexOf('.') !== 0;
264 | });
265 |
266 | for (let j = 0; j < driverJson.repair.length; j++) {
267 | const driverRepairView = driverJson.repair[j];
268 |
269 | if (driverRepairView.$template) {
270 | const viewId = driverRepairView.id;
271 | const templateId = driverRepairView.$template;
272 | if (!composeRepairViews.includes(templateId)) {
273 | throw new Error(`Invalid repair template for driver ${driverId}: ${templateId}`);
274 | }
275 | if (!viewId || typeof viewId !== 'string') {
276 | throw new Error(
277 | `Invalid repair template "id" property for driver ${driverId}: ${templateId}`,
278 | );
279 | }
280 |
281 | await fse.ensureDir(appRepairPath);
282 |
283 | // copy html
284 | let html = await readFileAsync(path.join(composeRepairPath, templateId, 'index.html'));
285 | html = html.toString();
286 | html = html.replace(/{{assets}}/g, `${viewId}.assets`);
287 | await writeFileAsync(path.join(appRepairPath, `${viewId}.html`), html);
288 |
289 | // copy assets
290 | const composeRepairAssetsPath = path.join(composeRepairPath, templateId, 'assets');
291 | if (await fse.exists(composeRepairAssetsPath)) {
292 | await fse.copy(composeRepairAssetsPath, path.join(appRepairPath, `${viewId}.assets`));
293 | }
294 | }
295 |
296 | // set repair options
297 | if (driverJson.$repairOptions) {
298 | for (const [id, options] of Object.entries(driverJson.$repairOptions)) {
299 | const view = _.findWhere(driverJson.repair, { id });
300 | if (view) {
301 | view.options = view.options || {};
302 | Object.assign(view.options, options);
303 | }
304 | }
305 | }
306 | }
307 | }
308 |
309 | // merge flow
310 | try {
311 | driverJson.$flow = await this._getJsonFile(
312 | path.join(this._appPath, 'drivers', driverId, 'driver.flow.compose.json'),
313 | );
314 | } catch (err) {
315 | if (err.code !== 'ENOENT') throw new Error(err);
316 | }
317 |
318 | // get drivers flow templates
319 | const flowTemplates = {};
320 | try {
321 | for (let i = 0; i < FLOW_TYPES.length; i++) {
322 | const type = FLOW_TYPES[i];
323 | const typePath = path.join(this._appPathCompose, 'drivers', 'flow', type);
324 | flowTemplates[type] = await this._getJsonFiles(typePath);
325 | }
326 | } catch (err) {
327 | if (err.code !== 'ENOENT') throw new Error(err);
328 | }
329 |
330 | if (
331 | typeof driverJson.$flow === 'object'
332 | && driverJson.$flow !== null
333 | && !Array.isArray(driverJson.$flow)
334 | ) {
335 | for (let i = 0; i < FLOW_TYPES.length; i++) {
336 | const type = FLOW_TYPES[i];
337 | const cards = driverJson.$flow[type];
338 | if (!cards) continue;
339 |
340 | for (let j = 0; j < cards.length; j++) {
341 | const card = cards[j];
342 |
343 | // extend card if possible
344 | if (card.$extends) {
345 | const templateIds = [].concat(card.$extends);
346 | const templateCards = flowTemplates[type];
347 |
348 | let flowTemplate = {};
349 | for (const templateId of templateIds) {
350 | if (!templateCards[templateId]) {
351 | throw new Error(
352 | `Invalid driver flow template for driver ${driverId}: ${templateId}`,
353 | );
354 | }
355 | flowTemplate = Object.assign(flowTemplate, templateCards[templateId]);
356 | }
357 |
358 | // assign template to original flow object
359 | Object.assign(card, {
360 | id: card.$id || templateIds[templateIds.length - 1],
361 | ...flowTemplate,
362 | ...card,
363 | });
364 | }
365 |
366 | let filter = '';
367 | if (typeof card.$filter === 'string') {
368 | filter = card.$filter;
369 | } else if (typeof card.$filter === 'object' && card.$filter !== null) {
370 | filter = new url.URLSearchParams(card.$filter).toString();
371 | }
372 |
373 | card.args = card.args || [];
374 | card.args.unshift({
375 | type: 'device',
376 | name: card.$deviceName || 'device',
377 | filter: `driver_id=${driverId}${filter ? `&${filter}` : ''}`,
378 | });
379 |
380 | await this._addFlowCard({
381 | type,
382 | card,
383 | });
384 | }
385 | }
386 | }
387 |
388 | // add driver to app.json
389 | this._appJson.drivers = this._appJson.drivers || [];
390 | this._appJson.drivers.push(driverJson);
391 |
392 | Log.info(`Added Driver \`${driverId}\``);
393 | }
394 | }
395 |
396 | /*
397 | Find widgets in /widgets/:id/widget.compose.json
398 | */
399 | async _composeWidgets() {
400 | // dont delete merge with widgets that dont have compose
401 | // delete this._appJson.widgets;
402 |
403 | // use _getChildFolders to prevent any library or documentation files
404 | // ending up in the driver list.
405 | const widgets = await this._getChildFolders(path.join(this._appPath, 'widgets'));
406 |
407 | for (let widgetIndex = 0; widgetIndex < widgets.length; widgetIndex++) {
408 | const widgetId = widgets[widgetIndex];
409 | if (widgetId.indexOf('.') === 0) continue;
410 |
411 | // merge json
412 | const widgetJson = await this._getJsonFile(
413 | path.join(this._appPath, 'widgets', widgetId, 'widget.compose.json'),
414 | ).catch(err => {
415 | if (err.code !== 'ENOENT') throw new Error(err);
416 | return null;
417 | });
418 |
419 | if (widgetJson == null) {
420 | continue;
421 | }
422 |
423 | widgetJson.id = widgetId;
424 |
425 | if (widgetJson.settings == null) {
426 | widgetJson.settings = [];
427 | }
428 |
429 | this._appJson.widgets = this._appJson.widgets || {};
430 | this._appJson.widgets[widgetJson.id] = widgetJson;
431 |
432 | Log.info(`Added Widget \`${widgetId}\``);
433 | }
434 | }
435 |
436 | replaceSpecialPropertiesRecursive(obj, driverId, driverJson, zwaveParameterIndex) {
437 | if (typeof obj !== 'object' || obj === null) return obj;
438 |
439 | // store last found zwave parameter index
440 | if (
441 | Object.prototype.hasOwnProperty.call(obj, 'zwave')
442 | && Object.prototype.hasOwnProperty.call(obj.zwave, 'index')
443 | ) {
444 | zwaveParameterIndex = obj.zwave.index;
445 | }
446 |
447 | for (const key of Object.keys(obj)) {
448 | if (typeof obj[key] === 'string') {
449 | obj[key] = obj[key].replace(/{{driverId}}/g, driverId);
450 |
451 | try {
452 | obj[key] = obj[key].replace(/{{driverName}}/g, driverJson.name.en);
453 |
454 | for (const locale of HomeyLib.App.getLocales()) {
455 | const replacement = driverJson.name[locale] || driverJson.name.en;
456 | obj[key] = obj[key].replace(
457 | new RegExp(
458 | `{{driverName${locale.charAt(0).toUpperCase()}${locale.charAt(1).toLowerCase()}}}`,
459 | 'g',
460 | ),
461 | replacement,
462 | );
463 | }
464 | } catch (err) {
465 | throw new Error(`Missing property \`name\` in driver ${driverId}`);
466 | }
467 | obj[key] = obj[key].replace(/{{driverPath}}/g, `/drivers/${driverId}`);
468 | obj[key] = obj[key].replace(/{{driverAssetsPath}}/g, `/drivers/${driverId}/assets`);
469 |
470 | if (zwaveParameterIndex) {
471 | obj[key] = obj[key].replace(/{{zwaveParameterIndex}}/g, zwaveParameterIndex);
472 | }
473 | } else {
474 | obj[key] = this.replaceSpecialPropertiesRecursive(
475 | obj[key],
476 | driverId,
477 | driverJson,
478 | zwaveParameterIndex,
479 | );
480 | }
481 | }
482 | return obj;
483 | }
484 |
485 | /*
486 | Find signals in /compose/signals/:frequency/:id
487 | */
488 | async _composeSignals() {
489 | delete this._appJson.signals;
490 |
491 | const frequencies = ['433', '868', 'ir'];
492 | for (let i = 0; i < frequencies.length; i++) {
493 | const frequency = frequencies[i];
494 |
495 | const signals = await this._getJsonFiles(
496 | path.join(this._appPathCompose, 'signals', frequency),
497 | );
498 |
499 | for (const [_signalId, signal] of Object.entries(signals)) {
500 | const signalId = signal.$id || path.basename(_signalId, '.json');
501 |
502 | this._appJson.signals = this._appJson.signals || {};
503 | this._appJson.signals[frequency] = this._appJson.signals[frequency] || {};
504 | this._appJson.signals[frequency][signalId] = signal;
505 |
506 | Log.info(`Added Signal \`${signalId}\` for frequency \`${frequency}\``);
507 | }
508 | }
509 | }
510 |
511 | /*
512 | Find flow cards in /compose/flow/:type/:id
513 | */
514 | async _composeFlow() {
515 | delete this._appJson.flow;
516 |
517 | for (let i = 0; i < FLOW_TYPES.length; i++) {
518 | const type = FLOW_TYPES[i];
519 |
520 | const typePath = path.join(this._appPathCompose, 'flow', type);
521 | const cards = await this._getJsonFiles(typePath);
522 | for (const [cardId, card] of Object.entries(cards)) {
523 | await this._addFlowCard({
524 | type,
525 | card,
526 | id: path.basename(cardId, '.json'),
527 | });
528 | }
529 | }
530 | }
531 |
532 | async _addFlowCard({ type, card, id }) {
533 | const cardId = card.$id || card.id || id;
534 | card.id = cardId;
535 |
536 | this._appJson.flow = this._appJson.flow || {};
537 | this._appJson.flow[type] = this._appJson.flow[type] || [];
538 | this._appJson.flow[type].push(card);
539 |
540 | Log.info(`Added FlowCard \`${cardId}\` for type \`${type}\``);
541 | }
542 |
543 | async _composeScreensavers() {
544 | delete this._appJson.screensavers;
545 |
546 | const screensavers = await this._getJsonFiles(path.join(this._appPathCompose, 'screensavers'));
547 | for (const [screensaverId, screensaver] of Object.entries(screensavers)) {
548 | screensaver.name = screensaver.$name || screensaver.name || screensaverId;
549 |
550 | this._appJson.screensavers = this._appJson.screensavers || [];
551 | this._appJson.screensavers.push(screensaver);
552 |
553 | Log.info(`Added Screensaver \`${screensaver.name}\``);
554 | }
555 | }
556 |
557 | async _composeCapabilities() {
558 | delete this._appJson.capabilities;
559 |
560 | const capabilities = await this._getJsonFiles(path.join(this._appPathCompose, 'capabilities'));
561 | for (const [_capabilityId, capability] of Object.entries(capabilities)) {
562 | const capabilityId = capability.$id || _capabilityId;
563 |
564 | this._appJson.capabilities = this._appJson.capabilities || {};
565 | this._appJson.capabilities[capabilityId] = capability;
566 |
567 | Log.info(`Added Capability \`${capabilityId}\``);
568 | }
569 | }
570 |
571 | async _composeDiscovery() {
572 | delete this._appJson.discovery;
573 |
574 | const strategies = await this._getJsonFiles(path.join(this._appPathCompose, 'discovery'));
575 | for (const [strategyId, strategy] of Object.entries(strategies)) {
576 | this._appJson.discovery = this._appJson.discovery || {};
577 | this._appJson.discovery[strategyId] = strategy;
578 | Log.info(`Added Discovery Strategy \`${strategyId}\``);
579 | }
580 | }
581 |
582 | /*
583 | Merge locales (deep merge). They are merged from long to small filename.
584 |
585 | Example files:
586 | /.homeycompose/locales/en.json (can contain any property, and $app, $drivers, $flow, $widgets)
587 | /.homeycompose/locales/en.foo.json (will be placed under property `foo`)
588 | /.homeycompose/locales/en.foo.bar.json (will be placed under property `foo.bar`)
589 | */
590 |
591 | async _composeLocales() {
592 | const appLocalesPath = path.join(this._appPath, 'locales');
593 | const appLocales = await this._getJsonFiles(appLocalesPath);
594 | const appLocalesChanged = [];
595 |
596 | const appComposeLocalesPath = path.join(this._appPathCompose, 'locales');
597 | const appComposeLocales = await this._getJsonFiles(appComposeLocalesPath);
598 |
599 | // sort locales to merge the longest paths first
600 | const sortedAppComposeLocaleIds = Object.keys(appComposeLocales).sort(
601 | (a, b) => b.split('.').length - a.split('.').length,
602 | );
603 |
604 | for (const appComposeLocaleId of sortedAppComposeLocaleIds) {
605 | const appComposeLocale = appComposeLocales[appComposeLocaleId];
606 | const appComposeLocaleIdArray = path.basename(appComposeLocaleId, '.json').split('.');
607 | const appComposeLocaleLanguage = appComposeLocaleIdArray.shift();
608 |
609 | appLocales[appComposeLocaleLanguage] = appLocales[appComposeLocaleLanguage] || {};
610 |
611 | if (appComposeLocaleIdArray.length === 0) {
612 | appLocales[appComposeLocaleLanguage] = deepmerge(
613 | appLocales[appComposeLocaleLanguage],
614 | appComposeLocale,
615 | );
616 | } else {
617 | const value = objectPath.get(appLocales[appComposeLocaleLanguage], appComposeLocaleIdArray);
618 |
619 | objectPath.set(
620 | appLocales[appComposeLocaleLanguage],
621 | appComposeLocaleIdArray,
622 | deepmerge(value || {}, appComposeLocale),
623 | );
624 | }
625 |
626 | if (!appLocalesChanged.includes(appComposeLocaleLanguage)) {
627 | appLocalesChanged.push(appComposeLocaleLanguage);
628 | }
629 | }
630 |
631 | // Merge $drivers, $flow, $capabilities, $widgets into /app.json
632 | for (let i = 0; i < appLocalesChanged.length; i++) {
633 | const appLocaleId = appLocalesChanged[i];
634 | const appLocale = appLocales[appLocaleId];
635 |
636 | // App
637 | if (appLocale.$app) {
638 | // App.name
639 | if (appLocale.$app.name) {
640 | this._appJson.name = this._appJson.name ?? {};
641 | this._appJson.name[appLocaleId] = appLocale.$app.name;
642 | }
643 |
644 | // App.description
645 | if (appLocale.$app.description) {
646 | this._appJson.description = this._appJson.description ?? {};
647 | this._appJson.description[appLocaleId] = appLocale.$app.description;
648 | }
649 |
650 | delete appLocale.$app;
651 | }
652 |
653 | // Capabilities
654 | if (appLocale.$capabilities) {
655 | for (const [capabilityId, capability] of Object.entries(appLocale.$capabilities)) {
656 | if (!this._appJson.capabilities?.[capabilityId]) continue;
657 |
658 | // Capability.title
659 | if (capability.title) {
660 | this._appJson.capabilities[capabilityId].title = this._appJson.capabilities[capabilityId].title ?? {};
661 | this._appJson.capabilities[capabilityId].title[appLocaleId] = capability.title;
662 | }
663 |
664 | // Capability.units
665 | if (capability.units) {
666 | this._appJson.capabilities[capabilityId].units = this._appJson.capabilities[capabilityId].units ?? {};
667 | this._appJson.capabilities[capabilityId].units[appLocaleId] = capability.units;
668 | }
669 | }
670 |
671 | delete appLocale.$capabilities;
672 | }
673 |
674 | // Drivers
675 | if (appLocale.$drivers) {
676 | for (const [driverId, driver] of Object.entries(appLocale.$drivers)) {
677 | const appJsonDriver = this._appJson.drivers.find(driver => driver.id === driverId);
678 | if (!appJsonDriver) continue;
679 |
680 | // Driver.name
681 | if (driver.name) {
682 | appJsonDriver.name = appJsonDriver.name ?? {};
683 | appJsonDriver.name[appLocaleId] = driver.name;
684 | }
685 |
686 | // Driver.capabilitiesOptions
687 | if (driver.capabilitiesOptions) {
688 | appJsonDriver.capabilitiesOptions = appJsonDriver.capabilitiesOptions ?? {};
689 |
690 | for (const [capabilityId, capabilityOptions] of Object.entries(driver.capabilitiesOptions)) {
691 | // Driver.capabilitiesOptions[].title
692 | if (capabilityOptions.title) {
693 | appJsonDriver.capabilitiesOptions[capabilityId] = appJsonDriver.capabilitiesOptions[capabilityId] ?? {};
694 | appJsonDriver.capabilitiesOptions[capabilityId].title = appJsonDriver.capabilitiesOptions[capabilityId].title ?? {};
695 | appJsonDriver.capabilitiesOptions[capabilityId].title[appLocaleId] = capabilityOptions.title;
696 | }
697 |
698 | // Driver.capabilitiesOptions[].units
699 | if (capabilityOptions.units) {
700 | appJsonDriver.capabilitiesOptions[capabilityId] = appJsonDriver.capabilitiesOptions[capabilityId] ?? {};
701 | appJsonDriver.capabilitiesOptions[capabilityId].units = appJsonDriver.capabilitiesOptions[capabilityId].units ?? {};
702 | appJsonDriver.capabilitiesOptions[capabilityId].units[appLocaleId] = capabilityOptions.units;
703 | }
704 | }
705 | }
706 |
707 | // Driver.pair
708 | // Driver.repair
709 | ['pair', 'repair'].forEach(pairType => {
710 | if (driver[pairType]) {
711 | for (const [viewId, view] of Object.entries(driver[pairType])) {
712 | const appJsonDriverView = appJsonDriver[pairType].find(view => view.id === viewId);
713 | if (!appJsonDriverView) continue;
714 |
715 | if (view.options) {
716 | for (const [key, value] of Object.entries(view.options)) {
717 | appJsonDriverView.options = appJsonDriverView.options ?? {};
718 | appJsonDriverView.options[key] = appJsonDriverView.options[key] ?? {};
719 | appJsonDriverView.options[key][appLocaleId] = value;
720 | }
721 | }
722 | }
723 | }
724 | });
725 |
726 | // Driver.settings
727 | if (driver.settings) {
728 | // Flatten settings
729 | const appJsonDriverSettingsFlat = appJsonDriver.settings.reduce((acc, setting) => {
730 | acc[setting.id] = setting;
731 | if (setting.children) {
732 | setting.children.forEach(child => {
733 | acc[child.id] = child;
734 | });
735 | }
736 | return acc;
737 | }, {});
738 |
739 | // Driver.settings
740 | for (const [settingId, setting] of Object.entries(driver.settings)) {
741 | const appJsonDriverSetting = appJsonDriverSettingsFlat[settingId];
742 | if (!appJsonDriverSetting) continue;
743 |
744 | // Driver.settings[].label
745 | if (setting.label) {
746 | appJsonDriverSetting.label = appJsonDriverSetting.label ?? {};
747 | appJsonDriverSetting.label[appLocaleId] = setting.label;
748 | }
749 |
750 | // Driver.settings[].hint
751 | if (setting.hint) {
752 | appJsonDriverSetting.hint = appJsonDriverSetting.hint ?? {};
753 | appJsonDriverSetting.hint[appLocaleId] = setting.hint;
754 | }
755 |
756 | // Driver.settings[].units
757 | if (setting.units) {
758 | appJsonDriverSetting.units = appJsonDriverSetting.units ?? {};
759 | appJsonDriverSetting.units[appLocaleId] = setting.units;
760 | }
761 |
762 | // Driver.settings[].values
763 | if (setting.values) {
764 | for (const [valueId, value] of Object.entries(setting.values)) {
765 | const appJsonDriverSettingValue = appJsonDriverSetting.values.find(value => value.id === valueId);
766 | if (!appJsonDriverSettingValue) continue;
767 |
768 | // Driver.settings[].values[].label
769 | if (value.label) {
770 | appJsonDriverSettingValue.label = appJsonDriverSettingValue.label ?? {};
771 | appJsonDriverSettingValue.label[appLocaleId] = value.label;
772 | }
773 | }
774 | }
775 | }
776 |
777 | // Driver.zwave
778 | if (driver.zwave) {
779 | appJsonDriver.zwave = appJsonDriver.zwave ?? {};
780 |
781 | if (driver.zwave.learnmode) {
782 | appJsonDriver.zwave.learnmode = appJsonDriver.zwave.learnmode ?? {};
783 |
784 | // Driver.zwave.learnmode.instruction
785 | if (driver.zwave.learnmode?.instruction) {
786 | appJsonDriver.zwave.learnmode.instruction[appLocaleId] = driver.zwave.learnmode.instruction;
787 | }
788 | }
789 |
790 | // Driver.zwave.associationGroupsOptions
791 | if (driver.zwave.associationGroupsOptions) {
792 | appJsonDriver.zwave.associationGroupsOptions = appJsonDriver.zwave.associationGroupsOptions ?? {};
793 |
794 | for (const [associationGroupId, associationGroup] of Object.entries(driver.zwave.associationGroupsOptions)) {
795 | appJsonDriver.zwave.associationGroupsOptions[associationGroupId] = appJsonDriver.zwave.associationGroupsOptions[associationGroupId] ?? {};
796 |
797 | // Driver.zwave.associationGroupsOptions[].hint
798 | if (associationGroup.hint) {
799 | appJsonDriver.zwave.associationGroupsOptions[associationGroupId].hint = appJsonDriver.zwave.associationGroupsOptions[associationGroupId].hint ?? {};
800 | appJsonDriver.zwave.associationGroupsOptions[associationGroupId].hint[appLocaleId] = associationGroup.hint;
801 | }
802 | }
803 | }
804 |
805 | // Driver.zwave.multiChannelNodes
806 | if (driver.zwave.multiChannelNodes) {
807 | appJsonDriver.zwave.multiChannelNodes = appJsonDriver.zwave.multiChannelNodes ?? {};
808 |
809 | for (const [multiChannelNodeId, multiChannelNode] of Object.entries(driver.zwave.multiChannelNodes)) {
810 | appJsonDriver.zwave.multiChannelNodes[multiChannelNodeId] = appJsonDriver.zwave.multiChannelNodes[multiChannelNodeId] ?? {};
811 |
812 | // Driver.zwave.multiChannelNodes[].name
813 | if (multiChannelNode.name) {
814 | appJsonDriver.zwave.multiChannelNodes[multiChannelNodeId].name = appJsonDriver.zwave.multiChannelNodes[multiChannelNodeId].name ?? {};
815 | appJsonDriver.zwave.multiChannelNodes[multiChannelNodeId].name[appLocaleId] = multiChannelNode.name;
816 | }
817 | }
818 | }
819 | }
820 |
821 | // Driver.zigbee
822 | if (driver.zigbee) {
823 | appJsonDriver.zigbee = appJsonDriver.zigbee ?? {};
824 |
825 | if (driver.zigbee.learnmode) {
826 | appJsonDriver.zigbee.learnmode = appJsonDriver.zigbee.learnmode ?? {};
827 |
828 | // Driver.zigbee.learnmode.instruction
829 | if (driver.zigbee.learnmode?.instruction) {
830 | appJsonDriver.zigbee.learnmode.instruction[appLocaleId] = driver.zigbee.learnmode.instruction;
831 | }
832 | }
833 | }
834 |
835 | // Driver.matter
836 | if (driver.matter) {
837 | appJsonDriver.matter = appJsonDriver.matter ?? {};
838 |
839 | if (driver.matter.learnmode) {
840 | appJsonDriver.matter.learnmode = appJsonDriver.matter.learnmode ?? {};
841 |
842 | // Driver.matter.learnmode.instruction
843 | if (driver.matter.learnmode?.instruction) {
844 | appJsonDriver.matter.learnmode.instruction[appLocaleId] = driver.matter.learnmode.instruction;
845 | }
846 | }
847 | }
848 | }
849 | }
850 |
851 | delete appLocale.$drivers;
852 | }
853 |
854 | // Flow
855 | if (appLocale.$flow) {
856 | ['triggers', 'conditions', 'actions'].forEach(flowType => {
857 | if (!appLocale.$flow[flowType]) return;
858 |
859 | for (const [cardId, card] of Object.entries(appLocale.$flow[flowType])) {
860 | const appJsonFlowCard = this._appJson.flow?.[flowType]?.find(card => card.id === cardId);
861 | if (!appJsonFlowCard) continue;
862 |
863 | // Card.title
864 | if (card.title) {
865 | appJsonFlowCard.title = appJsonFlowCard.title ?? {};
866 | appJsonFlowCard.title[appLocaleId] = card.title;
867 | }
868 |
869 | // Card.titleFormatted
870 | if (card.titleFormatted) {
871 | appJsonFlowCard.titleFormatted = appJsonFlowCard.titleFormatted ?? {};
872 | appJsonFlowCard.titleFormatted[appLocaleId] = card.titleFormatted;
873 | }
874 |
875 | // Card.hint
876 | if (card.hint) {
877 | appJsonFlowCard.hint = appJsonFlowCard.hint ?? {};
878 | appJsonFlowCard.hint[appLocaleId] = card.hint;
879 | }
880 |
881 | // Card.args
882 | if (card.args) {
883 | for (const [argId, arg] of Object.entries(card.args)) {
884 | const appJsonFlowCardArg = appJsonFlowCard.args.find(arg => arg.name === argId);
885 | if (!appJsonFlowCardArg) continue;
886 |
887 | // Card.args[].title
888 | if (arg.title) {
889 | appJsonFlowCardArg.title = appJsonFlowCardArg.title ?? {};
890 | appJsonFlowCardArg.title[appLocaleId] = arg.title;
891 | }
892 |
893 | // Card.args[].label
894 | if (arg.label) {
895 | appJsonFlowCardArg.label = appJsonFlowCardArg.label ?? {};
896 | appJsonFlowCardArg.label[appLocaleId] = arg.label;
897 | }
898 |
899 | // Card.args[].placeholder
900 | if (arg.placeholder) {
901 | appJsonFlowCardArg.placeholder = appJsonFlowCardArg.placeholder ?? {};
902 | appJsonFlowCardArg.placeholder[appLocaleId] = arg.placeholder;
903 | }
904 |
905 | // Card.args[].values
906 | if (arg.values) {
907 | for (const [valueId, value] of Object.entries(arg.values)) {
908 | const appJsonFlowCardArgValue = appJsonFlowCardArg.values.find(value => value.id === valueId);
909 | if (!appJsonFlowCardArgValue) continue;
910 |
911 | // Card.args[].values[].title
912 | if (value.title) {
913 | appJsonFlowCardArgValue.title = appJsonFlowCardArgValue.title ?? {};
914 | appJsonFlowCardArgValue.title[appLocaleId] = value.title;
915 | }
916 | }
917 | }
918 | }
919 | }
920 |
921 | // Card.tokens
922 | if (card.tokens) {
923 | for (const [tokenId, token] of Object.entries(card.tokens)) {
924 | const appJsonFlowCardToken = appJsonFlowCard.tokens.find(token => token.name === tokenId);
925 | if (!appJsonFlowCardToken) continue;
926 |
927 | // Card.tokens[].title
928 | if (token.title) {
929 | appJsonFlowCardToken.title = appJsonFlowCardToken.title ?? {};
930 | appJsonFlowCardToken.title[appLocaleId] = token.title;
931 | }
932 |
933 | // Card.tokens[].example
934 | if (token.example) {
935 | appJsonFlowCardToken.example = appJsonFlowCardToken.example ?? {};
936 | appJsonFlowCardToken.example[appLocaleId] = token.example;
937 | }
938 | }
939 | }
940 | }
941 | });
942 |
943 | delete appLocale.$flow;
944 | }
945 |
946 | // Widgets
947 | if (appLocale.$widgets) {
948 | for (const [widgetId, widget] of Object.entries(appLocale.$widgets)) {
949 | const appJsonWidget = this._appJson.widgets?.[widgetId];
950 | if (!appJsonWidget) continue;
951 |
952 | // Widget.name
953 | if (widget.name) {
954 | appJsonWidget.name = appJsonWidget.name ?? {};
955 | appJsonWidget.name[appLocaleId] = widget.name;
956 | }
957 |
958 | // Widget.settings
959 | if (widget.settings) {
960 | for (const [settingId, setting] of Object.entries(widget.settings)) {
961 | const appJsonWidgetSetting = appJsonWidget.settings.find(setting => setting.id === settingId);
962 | if (!appJsonWidgetSetting) continue;
963 |
964 | // Widget.settings[].title
965 | if (setting.title) {
966 | appJsonWidgetSetting.title = appJsonWidgetSetting.title ?? {};
967 | appJsonWidgetSetting.title[appLocaleId] = setting.title;
968 | }
969 |
970 | // Widget.settings[].placeholder
971 | if (setting.placeholder) {
972 | appJsonWidgetSetting.placeholder = appJsonWidgetSetting.placeholder ?? {};
973 | appJsonWidgetSetting.placeholder[appLocaleId] = setting.placeholder;
974 | }
975 |
976 | // Widget.settings[].values
977 | if (setting.values) {
978 | for (const [valueId, value] of Object.entries(setting.values)) {
979 | const appJsonWidgetSettingValue = appJsonWidgetSetting.values.find(value => value.id === valueId);
980 | if (!appJsonWidgetSettingValue) continue;
981 |
982 | // Widget.settings[].values[].title
983 | if (value.title) {
984 | appJsonWidgetSettingValue.title = appJsonWidgetSettingValue.title ?? {};
985 | appJsonWidgetSettingValue.title[appLocaleId] = value.title;
986 | }
987 | }
988 | }
989 | }
990 | }
991 | }
992 | }
993 |
994 | delete appLocale.$widgets;
995 | }
996 |
997 | // Replace special properties in drivers
998 | if (Array.isArray(this._appJson.drivers)) {
999 | for (let i = 0; i < this._appJson.drivers.length; i++) {
1000 | const driver = this._appJson.drivers[i];
1001 | this.replaceSpecialPropertiesRecursive(driver, driver.id, driver);
1002 | }
1003 | }
1004 |
1005 | // Write app locales
1006 | for (let i = 0; i < appLocalesChanged.length; i++) {
1007 | const appLocaleId = appLocalesChanged[i];
1008 | const appLocale = appLocales[appLocaleId];
1009 | await writeFileAsync(
1010 | path.join(appLocalesPath, `${appLocaleId}.json`),
1011 | JSON.stringify(appLocale, false, 2),
1012 | );
1013 | Log.info(`Added Locale \`${appLocaleId}\``);
1014 | }
1015 | }
1016 |
1017 | async _saveAppJson() {
1018 | function removeDollarPropertiesRecursive(obj) {
1019 | if (typeof obj !== 'object' || obj === null) return obj;
1020 | for (const key of Object.keys(obj)) {
1021 | if (key.indexOf('$') === 0) {
1022 | delete obj[key];
1023 | } else {
1024 | obj[key] = removeDollarPropertiesRecursive(obj[key]);
1025 | }
1026 | }
1027 | return obj;
1028 | }
1029 |
1030 | let json = JSON.parse(JSON.stringify(this._appJson));
1031 | json = removeDollarPropertiesRecursive(json);
1032 |
1033 | await writeFileAsync(this._appJsonPath, JSON.stringify(json, false, 2));
1034 | }
1035 |
1036 | async _getChildFolders(rootPath) {
1037 | const childFolders = [];
1038 | try {
1039 | const pathContents = await readdirAsync(rootPath, { withFileTypes: true });
1040 |
1041 | // Check all paths for dirs
1042 | Object.values(pathContents).forEach(pathConent => {
1043 | if (pathConent.isDirectory()) {
1044 | childFolders.push(pathConent.name);
1045 | }
1046 | });
1047 |
1048 | return childFolders;
1049 | } catch (err) {
1050 | return childFolders;
1051 | }
1052 | }
1053 |
1054 | async _getFiles(filesPath) {
1055 | try {
1056 | const files = await readdirAsync(filesPath);
1057 |
1058 | return files
1059 | .filter(file => {
1060 | return file.indexOf('.') !== 0;
1061 | })
1062 | .sort((a, b) => {
1063 | a = path.basename(a, path.extname(a)).toLowerCase();
1064 | b = path.basename(b, path.extname(b)).toLowerCase();
1065 | return a.localeCompare(b);
1066 | });
1067 | } catch (err) {
1068 | return [];
1069 | }
1070 | }
1071 |
1072 | async _getJsonFiles(filesPath) {
1073 | const result = {};
1074 | const files = await this._getFiles(filesPath);
1075 | for (let i = 0; i < files.length; i++) {
1076 | const filePath = files[i];
1077 | if (path.extname(filePath) !== '.json') continue;
1078 |
1079 | const fileJson = await this._getJsonFile(path.join(filesPath, filePath));
1080 | const fileId = path.basename(filePath, '.json');
1081 |
1082 | result[fileId] = fileJson;
1083 | }
1084 | return result;
1085 | }
1086 |
1087 | async _getJsonFile(filePath) {
1088 | let fileJson = await readFileAsync(filePath);
1089 | try {
1090 | fileJson = JSON.parse(fileJson);
1091 | } catch (err) {
1092 | throw new Error(`Error in file ${filePath}\n${err.message}`);
1093 | }
1094 |
1095 | return fileJson;
1096 | }
1097 |
1098 | }
1099 |
1100 | module.exports = HomeyCompose;
1101 |
--------------------------------------------------------------------------------