├── .eslintignore ├── .eslintrc.js ├── .github └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── images ├── enter_data.png ├── select_addons.png ├── select_configure.png └── select_settings.png ├── index.js ├── manifest.json ├── package.json ├── package.sh └── thing-url-adapter.js /.eslintignore: -------------------------------------------------------------------------------- 1 | /.eslintrc.js 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'env': { 3 | 'browser': true, 4 | 'commonjs': true, 5 | 'es6': true, 6 | 'jasmine': true, 7 | 'jest': true, 8 | 'mocha': true, 9 | 'node': true 10 | }, 11 | 'extends': 'eslint:recommended', 12 | 'parser': 'babel-eslint', 13 | 'parserOptions': { 14 | 'sourceType': 'module' 15 | }, 16 | 'rules': { 17 | 'arrow-parens': [ 18 | 'error', 19 | 'always' 20 | ], 21 | 'arrow-spacing': 'error', 22 | 'block-scoped-var': 'error', 23 | 'block-spacing': [ 24 | 'error', 25 | 'always' 26 | ], 27 | 'brace-style': [ 28 | 'error', 29 | '1tbs' 30 | ], 31 | 'comma-dangle': [ 32 | 'error', 33 | 'always-multiline' 34 | ], 35 | 'comma-spacing': 'error', 36 | 'comma-style': [ 37 | 'error', 38 | 'last' 39 | ], 40 | 'computed-property-spacing': [ 41 | 'error', 42 | 'never' 43 | ], 44 | 'curly': 'error', 45 | 'dot-notation': 'error', 46 | 'eol-last': 'error', 47 | 'func-call-spacing': [ 48 | 'error', 49 | 'never' 50 | ], 51 | 'implicit-arrow-linebreak': [ 52 | 'error', 53 | 'beside' 54 | ], 55 | 'indent': [ 56 | 'error', 57 | 2, 58 | { 59 | 'ArrayExpression': 'first', 60 | 'CallExpression': { 61 | 'arguments': 'first' 62 | }, 63 | 'FunctionDeclaration': { 64 | 'parameters': 'first' 65 | }, 66 | 'FunctionExpression': { 67 | 'parameters': 'first' 68 | }, 69 | 'ObjectExpression': 'first', 70 | 'SwitchCase': 1 71 | } 72 | ], 73 | 'key-spacing': [ 74 | 'error', 75 | { 76 | 'afterColon': true, 77 | 'beforeColon': false, 78 | 'mode': 'strict' 79 | } 80 | ], 81 | 'keyword-spacing': [ 82 | 'error', 83 | { 84 | 'after': true, 85 | 'before': true 86 | } 87 | ], 88 | 'linebreak-style': [ 89 | 'error', 90 | 'unix' 91 | ], 92 | 'lines-between-class-members': [ 93 | 'error', 94 | 'always' 95 | ], 96 | 'max-len': [ 97 | 'error', 98 | 80 99 | ], 100 | 'multiline-ternary': [ 101 | 'error', 102 | 'always-multiline' 103 | ], 104 | 'no-console': 0, 105 | 'no-duplicate-imports': 'error', 106 | 'no-eval': 'error', 107 | 'no-floating-decimal': 'error', 108 | 'no-implicit-globals': 'error', 109 | 'no-implied-eval': 'error', 110 | 'no-lonely-if': 'error', 111 | 'no-multi-spaces': [ 112 | 'error', 113 | { 114 | 'ignoreEOLComments': true 115 | } 116 | ], 117 | 'no-multiple-empty-lines': 'error', 118 | 'no-prototype-builtins': 'off', 119 | 'no-return-assign': 'error', 120 | 'no-script-url': 'error', 121 | 'no-self-compare': 'error', 122 | 'no-sequences': 'error', 123 | 'no-shadow-restricted-names': 'error', 124 | 'no-tabs': 'error', 125 | 'no-trailing-spaces': 'error', 126 | 'no-undefined': 'error', 127 | 'no-unmodified-loop-condition': 'error', 128 | 'no-unused-vars': [ 129 | 'error', 130 | { 131 | 'argsIgnorePattern': '^_', 132 | 'varsIgnorePattern': '^_' 133 | } 134 | ], 135 | 'no-useless-computed-key': 'error', 136 | 'no-useless-concat': 'error', 137 | 'no-useless-constructor': 'error', 138 | 'no-useless-return': 'error', 139 | 'no-var': 'error', 140 | 'no-void': 'error', 141 | 'no-whitespace-before-property': 'error', 142 | 'object-curly-newline': [ 143 | 'error', 144 | { 145 | 'consistent': true 146 | } 147 | ], 148 | 'object-curly-spacing': [ 149 | 'error', 150 | 'never' 151 | ], 152 | 'object-property-newline': [ 153 | 'error', 154 | { 155 | 'allowMultiplePropertiesPerLine': true 156 | } 157 | ], 158 | 'operator-linebreak': [ 159 | 'error', 160 | 'after' 161 | ], 162 | 'padded-blocks': [ 163 | 'error', 164 | { 165 | 'blocks': 'never' 166 | } 167 | ], 168 | 'prefer-const': 'error', 169 | 'prefer-template': 'error', 170 | 'quote-props': [ 171 | 'error', 172 | 'as-needed' 173 | ], 174 | 'quotes': [ 175 | 'error', 176 | 'single', 177 | { 178 | 'allowTemplateLiterals': true 179 | } 180 | ], 181 | 'semi': [ 182 | 'error', 183 | 'always' 184 | ], 185 | 'semi-spacing': [ 186 | 'error', 187 | { 188 | 'after': true, 189 | 'before': false 190 | } 191 | ], 192 | 'semi-style': [ 193 | 'error', 194 | 'last' 195 | ], 196 | 'space-before-blocks': [ 197 | 'error', 198 | 'always' 199 | ], 200 | 'space-before-function-paren': [ 201 | 'error', 202 | { 203 | 'anonymous': 'never', 204 | 'asyncArrow': 'always', 205 | 'named': 'never' 206 | } 207 | ], 208 | 'space-in-parens': [ 209 | 'error', 210 | 'never' 211 | ], 212 | 'space-infix-ops': 'error', 213 | 'space-unary-ops': [ 214 | 'error', 215 | { 216 | 'nonwords': false, 217 | 'words': true 218 | } 219 | ], 220 | 'spaced-comment': [ 221 | 'error', 222 | 'always', 223 | { 224 | 'block': { 225 | 'balanced': true, 226 | 'exceptions': [ 227 | '*' 228 | ] 229 | } 230 | } 231 | ], 232 | 'switch-colon-spacing': [ 233 | 'error', 234 | { 235 | 'after': true, 236 | 'before': false 237 | } 238 | ], 239 | 'template-curly-spacing': [ 240 | 'error', 241 | 'never' 242 | ], 243 | 'yoda': 'error' 244 | } 245 | }; 246 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | node-version: [ 17 | 10, 18 | 12, 19 | 14, 20 | ] 21 | steps: 22 | - uses: actions/checkout@v2 23 | - uses: actions/setup-node@v1 24 | with: 25 | node-version: ${{ matrix.node-version }} 26 | - name: Install dependencies 27 | run: | 28 | npm install 29 | - name: Lint with eslint 30 | run: | 31 | npm run lint 32 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-node@v1 14 | with: 15 | node-version: 8 16 | - name: Set release version 17 | run: echo "RELEASE_VERSION=${GITHUB_REF:11}" >> $GITHUB_ENV 18 | - name: Package project 19 | run: | 20 | ./package.sh 21 | - name: Create Release 22 | id: create_release 23 | uses: actions/create-release@v1.0.0 24 | env: 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | with: 27 | tag_name: ${{ github.ref }} 28 | release_name: Release ${{ env.RELEASE_VERSION }} 29 | draft: false 30 | prerelease: false 31 | - name: Upload Release Asset 32 | id: upload-release-asset 33 | uses: actions/upload-release-asset@v1.0.1 34 | env: 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 36 | with: 37 | upload_url: ${{ steps.create_release.outputs.upload_url }} 38 | asset_path: thing-url-adapter-${{ env.RELEASE_VERSION }}.tgz 39 | asset_name: thing-url-adapter-${{ env.RELEASE_VERSION }}.tgz 40 | asset_content_type: application/gnutar 41 | - name: Upload Release Asset Checksum 42 | id: upload-release-asset-checksum 43 | uses: actions/upload-release-asset@v1.0.1 44 | env: 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | with: 47 | upload_url: ${{ steps.create_release.outputs.upload_url }} 48 | asset_path: thing-url-adapter-${{ env.RELEASE_VERSION }}.tgz.sha256sum 49 | asset_name: thing-url-adapter-${{ env.RELEASE_VERSION }}.tgz.sha256sum 50 | asset_content_type: text/plain 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.tgz 3 | *~ 4 | SHA256SUMS 5 | node_modules/ 6 | package-lock.json 7 | yarn.lock 8 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Community Participation Guidelines 2 | 3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines. 4 | For more details, please read the 5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 6 | 7 | ## How to Report 8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. 9 | 10 | 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # thing-url-adapter 2 | 3 | This is an adapter add-on for [WebThings Gateway](https://github.com/WebThingsIO/gateway) which enables users to discover and add native web things to their gateway. 4 | 5 | **Note:** This adapter consumes [Web Thing Description](https://iot.mozilla.org/wot/#web-thing-description)s conforming to Mozilla's legacy [Web Thing API](https://iot.mozilla.org/wot) specification. It will eventually be superceded by the [wot-adapter](https://github.com/WebThingsIO/wot-adapter) which will consume W3C compliant [Thing Description](https://www.w3.org/TR/wot-thing-description/)s instead. 6 | 7 | ## Adding Web Things to Gateway 8 | * Usually, your custom web things should be auto-detected on the network via mDNS, so they should appear in the usual "Add Devices" screen. 9 | * If they're not auto-detected, you can click "Add by URL..." at the bottom of the page and use the URL of your web thing. 10 | * If you're trying to add a server that contains multiple web things, i.e. the "multiple-things" examples from the [webthing-python](https://github.com/WebThingsIO/webthing-python), [webthing-node](https://github.com/WebThingsIO/webthing-node), or [webthing-java](https://github.com/WebThingsIO/webthing-java) libraries, you'll have to add them individually. You can do so by addressing them numerically, i.e. `http://myserver.local:8888/0` and `http://myserver.local:8888/1`. 11 | 12 | ## Secure Web Things 13 | * Web things that require jwt, basic or digest authentication can be supported by adding configuration options on the adapter page. 14 | * To add a secure web thing: 15 | 16 | * Use the hamburger to open the side menu and select "Settings". 17 | 18 | ![select_settings.png](images/select_settings.png) 19 | 20 | * Select "Add-ons". 21 | 22 | ![select_addons.png](images/select_addons.png) 23 | 24 | * Find the Web Thing adapter and select "Configure". 25 | 26 | ![select_configure.png](images/select_configure.png) 27 | 28 | * Enter data relevant to the desired authentication method. 29 | * To manually enter device URLs with no authentication select 'none' for the method. 30 | 31 | ![enter_data.png](images/enter_data.png) 32 | 33 | * Save the entry by pressing "Apply" at the bottom of the page. 34 | -------------------------------------------------------------------------------- /images/enter_data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WebThingsIO/thing-url-adapter/177015f15250d2303f4d24b7ac0490cda999470a/images/enter_data.png -------------------------------------------------------------------------------- /images/select_addons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WebThingsIO/thing-url-adapter/177015f15250d2303f4d24b7ac0490cda999470a/images/select_addons.png -------------------------------------------------------------------------------- /images/select_configure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WebThingsIO/thing-url-adapter/177015f15250d2303f4d24b7ac0490cda999470a/images/select_configure.png -------------------------------------------------------------------------------- /images/select_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WebThingsIO/thing-url-adapter/177015f15250d2303f4d24b7ac0490cda999470a/images/select_settings.png -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * index.js - Loads the Test adapter. 3 | * 4 | * This Source Code Form is subject to the terms of the Mozilla Public 5 | * License, v. 2.0. If a copy of the MPL was not distributed with this 6 | * file, You can obtain one at http://mozilla.org/MPL/2.0/.* 7 | */ 8 | 9 | 'use strict'; 10 | 11 | module.exports = require('./thing-url-adapter'); 12 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "WebThingsIO", 3 | "description": "Native web thing support", 4 | "gateway_specific_settings": { 5 | "webthings": { 6 | "exec": "{nodeLoader} {path}", 7 | "primary_type": "adapter", 8 | "strict_max_version": "*", 9 | "strict_min_version": "0.10.0", 10 | "enabled": true 11 | } 12 | }, 13 | "homepage_url": "https://github.com/WebThingsIO/thing-url-adapter", 14 | "id": "thing-url-adapter", 15 | "license": "MPL-2.0", 16 | "manifest_version": 1, 17 | "name": "Web Thing", 18 | "options": { 19 | "default": { 20 | "urls": [], 21 | "pollInterval": 5 22 | }, 23 | "schema": { 24 | "type": "object", 25 | "required": [ 26 | "urls", 27 | "pollInterval" 28 | ], 29 | "properties": { 30 | "urls": { 31 | "type": "array", 32 | "items": { 33 | "type": "object", 34 | "required": [ 35 | "href" 36 | ], 37 | "properties": { 38 | "href": { 39 | "description": "Base URL of web thing", 40 | "type": "string" 41 | }, 42 | "authentication": { 43 | "description": "Authentication credentials", 44 | "type": "object", 45 | "required": [ 46 | "method" 47 | ], 48 | "properties": { 49 | "method": { 50 | "type": "string", 51 | "enum": [ 52 | "none", 53 | "jwt" 54 | ] 55 | }, 56 | "token": { 57 | "description": "Token (for JWT)", 58 | "type": "string" 59 | } 60 | } 61 | } 62 | } 63 | } 64 | }, 65 | "pollInterval": { 66 | "description": "The interval, in seconds, at which to poll property values.", 67 | "type": "number" 68 | } 69 | } 70 | } 71 | }, 72 | "short_name": "Web Thing", 73 | "version": "0.5.2" 74 | } 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "thing-url-adapter", 3 | "version": "0.5.2", 4 | "description": "Native web thing support", 5 | "author": "WebThingsIO", 6 | "main": "index.js", 7 | "scripts": { 8 | "lint": "eslint ." 9 | }, 10 | "homepage": "https://github.com/WebThingsIO/thing-url-adapter", 11 | "license": "MPL-2.0", 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/WebThingsIO/thing-url-adapter.git" 15 | }, 16 | "bugs": { 17 | "url": "https://github.com/WebThingsIO/thing-url-adapter/issues" 18 | }, 19 | "files": [ 20 | "LICENSE", 21 | "README.md", 22 | "SHA256SUMS", 23 | "index.js", 24 | "manifest.json", 25 | "thing-url-adapter.js" 26 | ], 27 | "dependencies": { 28 | "dnssd": "^0.4.1", 29 | "node-fetch": "^2.6.1", 30 | "ws": "^7.3.1" 31 | }, 32 | "devDependencies": { 33 | "babel-eslint": "^10.1.0", 34 | "eslint": "^7.10.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | rm -rf node_modules 4 | 5 | npm install --production 6 | 7 | shasum --algorithm 256 manifest.json package.json *.js LICENSE README.md > SHA256SUMS 8 | 9 | find node_modules \( -type f -o -type l \) -exec shasum --algorithm 256 {} \; >> SHA256SUMS 10 | 11 | TARFILE=`npm pack` 12 | 13 | tar xzf ${TARFILE} 14 | cp -r node_modules ./package 15 | tar czf ${TARFILE} package 16 | 17 | shasum --algorithm 256 ${TARFILE} > ${TARFILE}.sha256sum 18 | 19 | rm -rf SHA256SUMS package 20 | -------------------------------------------------------------------------------- /thing-url-adapter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * example-plugin-adapter.js - ThingURL adapter implemented as a plugin. 3 | * 4 | * This Source Code Form is subject to the terms of the Mozilla Public 5 | * License, v. 2.0. If a copy of the MPL was not distributed with this 6 | * file, You can obtain one at http://mozilla.org/MPL/2.0/.* 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const crypto = require('crypto'); 12 | const dnssd = require('dnssd'); 13 | const fetch = require('node-fetch'); 14 | const manifest = require('./manifest.json'); 15 | const {URL} = require('url'); 16 | const WebSocket = require('ws'); 17 | 18 | const { 19 | Adapter, 20 | Database, 21 | Device, 22 | Event, 23 | Property, 24 | } = require('gateway-addon'); 25 | 26 | let webthingBrowser; 27 | let subtypeBrowser; 28 | let httpBrowser; 29 | 30 | const ACTION_STATUS = 'actionStatus'; 31 | const ADD_EVENT_SUBSCRIPTION = 'addEventSubscription'; 32 | const EVENT = 'event'; 33 | const PROPERTY_STATUS = 'propertyStatus'; 34 | const SET_PROPERTY = 'setProperty'; 35 | 36 | const PING_INTERVAL = 30 * 1000; 37 | const POLL_INTERVAL = 5 * 1000; 38 | const WS_INITIAL_BACKOFF = 1000; 39 | const WS_MAX_BACKOFF = 30 * 1000; 40 | 41 | function getHeaders(authentication, includeContentType = false) { 42 | const headers = { 43 | Accept: 'application/json', 44 | }; 45 | 46 | if (includeContentType) { 47 | headers['Content-Type'] = 'application/json'; 48 | } 49 | 50 | switch (authentication.method) { 51 | case 'jwt': 52 | headers.Authorization = `Bearer ${authentication.token}`; 53 | break; 54 | case 'basic': 55 | case 'digest': 56 | default: 57 | // not implemented 58 | break; 59 | } 60 | 61 | return headers; 62 | } 63 | 64 | class ThingURLProperty extends Property { 65 | constructor(device, name, url, propertyDescription) { 66 | super(device, name, propertyDescription); 67 | this.url = url; 68 | this.setCachedValue(propertyDescription.value); 69 | this.device.notifyPropertyChanged(this); 70 | } 71 | 72 | /** 73 | * @method setValue 74 | * @returns {Promise} resolves to the updated value 75 | * 76 | * @note it is possible that the updated value doesn't match 77 | * the value passed in. 78 | */ 79 | setValue(value) { 80 | if (this.device.ws && this.device.ws.readyState === WebSocket.OPEN) { 81 | const msg = { 82 | messageType: SET_PROPERTY, 83 | data: {[this.name]: value}, 84 | }; 85 | 86 | this.device.ws.send(JSON.stringify(msg)); 87 | 88 | // If the value is the same, we probably won't get a propertyStatus back 89 | // via the WebSocket, so let's go ahead and notify now. 90 | if (value === this.value) { 91 | this.device.notifyPropertyChanged(this); 92 | } 93 | 94 | return Promise.resolve(value); 95 | } 96 | 97 | return fetch(this.url, { 98 | method: 'PUT', 99 | headers: getHeaders(this.device.authentication, true), 100 | body: JSON.stringify({ 101 | [this.name]: value, 102 | }), 103 | }).then((res) => { 104 | return res.json(); 105 | }).then((response) => { 106 | const updatedValue = response[this.name]; 107 | this.setCachedValue(updatedValue); 108 | this.device.notifyPropertyChanged(this); 109 | return updatedValue; 110 | }).catch((e) => { 111 | console.log(`Failed to set ${this.name}: ${e}`); 112 | return this.value; 113 | }); 114 | } 115 | } 116 | 117 | class ThingURLDevice extends Device { 118 | constructor(adapter, id, url, authentication, description, mdnsUrl) { 119 | super(adapter, id); 120 | this.title = this.name = description.title || description.name; 121 | this.type = description.type; 122 | this['@context'] = 123 | description['@context'] || 'https://iot.mozilla.org/schemas'; 124 | this['@type'] = description['@type'] || []; 125 | this.url = url; 126 | this.authentication = authentication || {}; 127 | this.mdnsUrl = mdnsUrl; 128 | this.actionsUrl = null; 129 | this.eventsUrl = null; 130 | this.allPropertiesUrl = null; 131 | this.wsUrl = null; 132 | this.description = description.description; 133 | this.propertyPromises = []; 134 | this.ws = null; 135 | this.wsBackoff = WS_INITIAL_BACKOFF; 136 | this.pingInterval = null; 137 | this.requestedActions = new Map(); 138 | this.baseHref = new URL(url).origin; 139 | this.notifiedEvents = new Set(); 140 | this.scheduledUpdate = null; 141 | this.closing = false; 142 | 143 | for (const actionName in description.actions) { 144 | const action = description.actions[actionName]; 145 | if (action.hasOwnProperty('links')) { 146 | action.links = action.links.map((l) => { 147 | if (!l.href.startsWith('http://') && !l.href.startsWith('https://')) { 148 | l.proxy = true; 149 | } 150 | return l; 151 | }); 152 | } 153 | this.addAction(actionName, action); 154 | } 155 | 156 | for (const eventName in description.events) { 157 | const event = description.events[eventName]; 158 | if (event.hasOwnProperty('links')) { 159 | event.links = event.links.map((l) => { 160 | if (!l.href.startsWith('http://') && !l.href.startsWith('https://')) { 161 | l.proxy = true; 162 | } 163 | return l; 164 | }); 165 | } 166 | this.addEvent(eventName, event); 167 | } 168 | 169 | // If a websocket endpoint exists, connect to it. 170 | if (description.hasOwnProperty('links')) { 171 | for (const link of description.links) { 172 | if (link.rel === 'actions') { 173 | this.actionsUrl = this.baseHref + link.href; 174 | } else if (link.rel === 'events') { 175 | this.eventsUrl = this.baseHref + link.href; 176 | } else if (link.rel === 'properties') { 177 | this.allPropertiesUrl = this.baseHref + link.href; 178 | } else if (link.rel === 'alternate') { 179 | if (link.mediaType === 'text/html') { 180 | if (!link.href.startsWith('http://') && 181 | !link.href.startsWith('https://')) { 182 | link.proxy = true; 183 | } 184 | this.links.push(link); 185 | } else if (link.href.startsWith('ws://') || 186 | link.href.startsWith('wss://')) { 187 | this.wsUrl = link.href; 188 | } else { 189 | this.links.push(link); 190 | } 191 | } else { 192 | if (!link.href.startsWith('http://') && 193 | !link.href.startsWith('https://')) { 194 | link.proxy = true; 195 | } 196 | this.links.push(link); 197 | } 198 | } 199 | } 200 | 201 | if (this.allPropertiesUrl) { 202 | this.allPropertyValuesPromise = fetch(this.allPropertiesUrl, { 203 | headers: getHeaders(this.authentication), 204 | }).then((res) => { 205 | return res.json(); 206 | }); 207 | } 208 | 209 | for (const propertyName in description.properties) { 210 | const propertyDescription = description.properties[propertyName]; 211 | 212 | let propertyUrl; 213 | if (propertyDescription.hasOwnProperty('links')) { 214 | for (const link of propertyDescription.links) { 215 | if (!link.rel || link.rel === 'property') { 216 | propertyUrl = this.baseHref + link.href; 217 | break; 218 | } 219 | } 220 | } 221 | 222 | if (!propertyUrl) { 223 | if (!propertyDescription.href) { 224 | continue; 225 | } 226 | 227 | propertyUrl = this.baseHref + propertyDescription.href; 228 | } 229 | 230 | let propertyValuePromise; 231 | if (this.allPropertiesUrl) { 232 | propertyValuePromise = this.allPropertyValuesPromise; 233 | } else { 234 | propertyValuePromise = fetch(propertyUrl, { 235 | headers: getHeaders(this.authentication), 236 | }).then((res) => { 237 | return res.json(); 238 | }); 239 | } 240 | 241 | this.propertyPromises.push( 242 | propertyValuePromise.then((res) => { 243 | propertyDescription.value = res[propertyName]; 244 | if (propertyDescription.hasOwnProperty('links')) { 245 | propertyDescription.links = propertyDescription.links.map((l) => { 246 | if (!l.href.startsWith('http://') && 247 | !l.href.startsWith('https://')) { 248 | l.proxy = true; 249 | } 250 | return l; 251 | }); 252 | } 253 | const property = new ThingURLProperty( 254 | this, propertyName, propertyUrl, propertyDescription); 255 | this.properties.set(propertyName, property); 256 | }).catch((e) => { 257 | console.log(`Failed to connect to ${propertyUrl}: ${e}`); 258 | }) 259 | ); 260 | } 261 | 262 | this.allPropertyValuesPromise = null; 263 | 264 | this.startReading(); 265 | } 266 | 267 | startReading(now = false) { 268 | // If this is a recent gateway version, we hold off on polling/opening the 269 | // WebSocket until the user has actually saved the device. 270 | if (Adapter.prototype.hasOwnProperty('handleDeviceSaved') && !now) { 271 | return; 272 | } 273 | 274 | if (this.wsUrl) { 275 | if (!this.ws) { 276 | this.createWebSocket(); 277 | } 278 | } else { 279 | // If there's no websocket endpoint, poll the device for updates. 280 | // eslint-disable-next-line no-lonely-if 281 | if (!this.scheduledUpdate) { 282 | Promise.all(this.propertyPromises).then(() => this.poll()); 283 | } 284 | } 285 | } 286 | 287 | closeWebSocket() { 288 | this.closing = true; 289 | if (this.ws !== null) { 290 | if (this.ws.readyState === WebSocket.OPEN) { 291 | this.ws.close(); 292 | } 293 | 294 | // Allow the cleanup code in createWebSocket to handle shutdown 295 | } else if (this.scheduledUpdate) { 296 | clearTimeout(this.scheduledUpdate); 297 | } 298 | } 299 | 300 | createWebSocket() { 301 | if (this.closing) { 302 | return; 303 | } 304 | 305 | let auth = ''; 306 | switch (this.authentication.method) { 307 | case 'jwt': 308 | if (this.wsUrl.indexOf('?') >= 0) { 309 | auth = `&jwt=${this.authentication.token}`; 310 | } else { 311 | auth = `?jwt=${this.authentication.token}`; 312 | } 313 | break; 314 | case 'basic': 315 | case 'digest': 316 | default: 317 | // not implemented 318 | break; 319 | } 320 | 321 | this.ws = new WebSocket(`${this.wsUrl}${auth}`); 322 | 323 | this.ws.on('open', () => { 324 | this.connectedNotify(true); 325 | this.wsBackoff = WS_INITIAL_BACKOFF; 326 | 327 | if (this.events.size > 0) { 328 | // Subscribe to all events 329 | const msg = { 330 | messageType: ADD_EVENT_SUBSCRIPTION, 331 | data: {}, 332 | }; 333 | 334 | this.events.forEach((_value, key) => { 335 | msg.data[key] = {}; 336 | }); 337 | 338 | this.ws.send(JSON.stringify(msg)); 339 | } 340 | 341 | this.pingInterval = setInterval(() => { 342 | this.ws.ping(); 343 | }, PING_INTERVAL); 344 | }); 345 | 346 | this.ws.on('message', (data) => { 347 | try { 348 | const msg = JSON.parse(data); 349 | 350 | switch (msg.messageType) { 351 | case PROPERTY_STATUS: { 352 | for (const [name, value] of Object.entries(msg.data)) { 353 | const property = this.findProperty(name); 354 | if (property) { 355 | property.getValue().then((oldValue) => { 356 | if (value !== oldValue) { 357 | property.setCachedValue(value); 358 | this.notifyPropertyChanged(property); 359 | } 360 | }); 361 | } 362 | } 363 | break; 364 | } 365 | case ACTION_STATUS: { 366 | for (const action of Object.values(msg.data)) { 367 | const requestedAction = this.requestedActions.get(action.href); 368 | if (requestedAction) { 369 | requestedAction.status = action.status; 370 | requestedAction.timeRequested = action.timeRequested; 371 | requestedAction.timeCompleted = action.timeCompleted; 372 | this.actionNotify(requestedAction); 373 | } 374 | } 375 | break; 376 | } 377 | case EVENT: { 378 | for (const [name, event] of Object.entries(msg.data)) { 379 | this.createEvent(name, event); 380 | } 381 | break; 382 | } 383 | } 384 | } catch (e) { 385 | console.log(`Error receiving websocket message: ${e}`); 386 | } 387 | }); 388 | 389 | const cleanupAndReopen = () => { 390 | this.connectedNotify(false); 391 | 392 | if (this.pingInterval) { 393 | clearInterval(this.pingInterval); 394 | this.pingInterval = null; 395 | } 396 | 397 | this.ws.removeAllListeners('close'); 398 | this.ws.removeAllListeners('error'); 399 | this.ws.close(); 400 | this.ws = null; 401 | 402 | setTimeout(() => { 403 | this.wsBackoff = Math.min(this.wsBackoff * 2, WS_MAX_BACKOFF); 404 | this.createWebSocket(); 405 | }, this.wsBackoff); 406 | }; 407 | 408 | this.ws.on('close', cleanupAndReopen); 409 | this.ws.on('error', cleanupAndReopen); 410 | } 411 | 412 | async poll() { 413 | if (this.closing) { 414 | return; 415 | } 416 | 417 | try { 418 | // Update properties 419 | if (this.allPropertiesUrl) { 420 | const res = await fetch(this.allPropertiesUrl, { 421 | headers: getHeaders(this.authentication), 422 | }); 423 | const json = await res.json(); 424 | for (const prop of this.properties.values()) { 425 | const newValue = json[prop.name]; 426 | const value = await prop.getValue(); 427 | if (value !== newValue) { 428 | prop.setCachedValue(newValue); 429 | this.notifyPropertyChanged(prop); 430 | } 431 | } 432 | } else { 433 | await Promise.all(Array.from(this.properties.values()).map((prop) => { 434 | return fetch(prop.url, { 435 | headers: getHeaders(this.authentication), 436 | }).then((res) => { 437 | return res.json(); 438 | }).then((res) => { 439 | const newValue = res[prop.name]; 440 | prop.getValue().then((value) => { 441 | if (value !== newValue) { 442 | prop.setCachedValue(newValue); 443 | this.notifyPropertyChanged(prop); 444 | } 445 | }); 446 | }); 447 | })); 448 | } 449 | // Check for new actions 450 | if (this.actionsUrl !== null) { 451 | const res = await fetch(this.actionsUrl, { 452 | headers: getHeaders(this.authentication), 453 | }); 454 | const actions = await res.json(); 455 | for (let action of actions) { 456 | const actionName = Object.keys(action)[0]; 457 | action = action[actionName]; 458 | const requestedAction = 459 | this.requestedActions.get(action.href); 460 | 461 | if (requestedAction && action.status !== requestedAction.status) { 462 | requestedAction.status = action.status; 463 | requestedAction.timeRequested = action.timeRequested; 464 | requestedAction.timeCompleted = action.timeCompleted; 465 | this.actionNotify(requestedAction); 466 | } 467 | } 468 | } 469 | // Check for new events 470 | if (this.eventsUrl !== null) { 471 | const res = await fetch(this.eventsUrl, { 472 | headers: getHeaders(this.authentication), 473 | }); 474 | const events = await res.json(); 475 | for (let event of events) { 476 | const eventName = Object.keys(event)[0]; 477 | event = event[eventName]; 478 | this.createEvent(eventName, event); 479 | } 480 | } 481 | 482 | this.connectedNotify(true); 483 | } catch (e) { 484 | console.log(`Failed to poll device: ${e}`); 485 | this.connectedNotify(false); 486 | } 487 | 488 | if (this.scheduledUpdate) { 489 | clearTimeout(this.scheduledUpdate); 490 | } 491 | 492 | this.scheduledUpdate = setTimeout( 493 | () => this.poll(), 494 | this.adapter.pollInterval 495 | ); 496 | } 497 | 498 | createEvent(eventName, event) { 499 | const eventId = (event.data && event.data.hasOwnProperty('id')) ? 500 | event.data.id : 501 | `${eventName}-${event.timestamp}`; 502 | 503 | if (this.notifiedEvents.has(eventId)) { 504 | return; 505 | } 506 | if (!event.hasOwnProperty('timestamp')) { 507 | event.timestamp = new Date().toISOString(); 508 | } 509 | this.notifiedEvents.add(eventId); 510 | const e = new Event(this, 511 | eventName, 512 | event.data || null); 513 | e.timestamp = event.timestamp; 514 | 515 | this.eventNotify(e); 516 | } 517 | 518 | performAction(action) { 519 | action.start(); 520 | return fetch(this.actionsUrl, { 521 | method: 'POST', 522 | headers: getHeaders(this.authentication, true), 523 | body: JSON.stringify({[action.name]: {input: action.input}}), 524 | }).then((res) => { 525 | return res.json(); 526 | }).then((res) => { 527 | this.requestedActions.set(res[action.name].href, action); 528 | }).catch((e) => { 529 | console.log(`Failed to perform action: ${e}`); 530 | action.status = 'error'; 531 | this.actionNotify(action); 532 | }); 533 | } 534 | 535 | cancelAction(actionId, actionName) { 536 | let promise; 537 | 538 | this.requestedActions.forEach((action, actionHref) => { 539 | if (action.name === actionName && action.id === actionId) { 540 | promise = fetch(actionHref, { 541 | method: 'DELETE', 542 | headers: getHeaders(this.authentication), 543 | }).catch((e) => { 544 | console.log(`Failed to cancel action: ${e}`); 545 | }); 546 | 547 | this.requestedActions.delete(actionHref); 548 | } 549 | }); 550 | 551 | if (!promise) { 552 | promise = Promise.resolve(); 553 | } 554 | 555 | return promise; 556 | } 557 | } 558 | 559 | class ThingURLAdapter extends Adapter { 560 | constructor(addonManager) { 561 | super(addonManager, manifest.id, manifest.id); 562 | addonManager.addAdapter(this); 563 | this.knownUrls = {}; 564 | this.savedDevices = new Set(); 565 | this.pollInterval = POLL_INTERVAL; 566 | } 567 | 568 | async loadThing(url, retryCounter) { 569 | if (typeof retryCounter === 'undefined') { 570 | retryCounter = 0; 571 | } 572 | 573 | const href = url.href.replace(/\/$/, ''); 574 | 575 | if (!this.knownUrls[href]) { 576 | this.knownUrls[href] = { 577 | href, 578 | authentication: url.authentication, 579 | digest: '', 580 | timestamp: 0, 581 | }; 582 | } 583 | 584 | if (this.knownUrls[href].timestamp + 5000 > Date.now()) { 585 | return; 586 | } 587 | 588 | let res; 589 | try { 590 | res = await fetch(href, {headers: getHeaders(url.authentication)}); 591 | } catch (e) { 592 | // Retry the connection at a 2 second interval up to 5 times. 593 | if (retryCounter >= 5) { 594 | console.log(`Failed to connect to ${href}: ${e}`); 595 | } else { 596 | setTimeout(() => this.loadThing(url, retryCounter + 1), 2000); 597 | } 598 | 599 | return; 600 | } 601 | 602 | const text = await res.text(); 603 | 604 | const hash = crypto.createHash('md5'); 605 | hash.update(text); 606 | const dig = hash.digest('hex'); 607 | let known = false; 608 | if (this.knownUrls[href].digest === dig) { 609 | known = true; 610 | } 611 | 612 | this.knownUrls[href] = { 613 | href, 614 | authentication: url.authentication, 615 | digest: dig, 616 | timestamp: Date.now(), 617 | }; 618 | 619 | let data; 620 | try { 621 | data = JSON.parse(text); 622 | } catch (e) { 623 | console.log(`Failed to parse description at ${href}: ${e}`); 624 | return; 625 | } 626 | 627 | let things; 628 | if (Array.isArray(data)) { 629 | things = data; 630 | } else { 631 | things = [data]; 632 | } 633 | 634 | for (const thingDescription of things) { 635 | let thingUrl = href; 636 | if (thingDescription.hasOwnProperty('href')) { 637 | const baseHref = new URL(href).origin; 638 | thingUrl = baseHref + thingDescription.href; 639 | } 640 | 641 | const id = thingUrl.replace(/[:/]/g, '-'); 642 | if (id in this.devices) { 643 | if (known) { 644 | continue; 645 | } 646 | await this.removeThing(this.devices[id], true); 647 | } 648 | 649 | await this.addDevice( 650 | id, 651 | thingUrl, 652 | url.authentication, 653 | thingDescription, 654 | href 655 | ); 656 | } 657 | } 658 | 659 | unloadThing(url) { 660 | url = url.replace(/\/$/, ''); 661 | 662 | for (const id in this.devices) { 663 | const device = this.devices[id]; 664 | if (device.mdnsUrl === url) { 665 | device.closeWebSocket(); 666 | this.removeThing(device, true); 667 | } 668 | } 669 | 670 | if (this.knownUrls[url]) { 671 | delete this.knownUrls[url]; 672 | } 673 | } 674 | 675 | /** 676 | * Add a ThingURLDevice to the ThingURLAdapter 677 | * 678 | * @param {String} deviceId ID of the device to add. 679 | * @return {Promise} which resolves to the device added. 680 | */ 681 | addDevice(deviceId, deviceURL, authentication, description, mdnsUrl) { 682 | return new Promise((resolve, reject) => { 683 | if (deviceId in this.devices) { 684 | reject(`Device: ${deviceId} already exists.`); 685 | } else { 686 | const device = new ThingURLDevice( 687 | this, 688 | deviceId, 689 | deviceURL, 690 | authentication, 691 | description, 692 | mdnsUrl 693 | ); 694 | Promise.all(device.propertyPromises).then(() => { 695 | this.handleDeviceAdded(device); 696 | 697 | if (this.savedDevices.has(deviceId)) { 698 | device.startReading(true); 699 | } 700 | 701 | resolve(device); 702 | }).catch((e) => reject(e)); 703 | } 704 | }); 705 | } 706 | 707 | /** 708 | * Handle a user saving a device. Note that incoming devices may not be for 709 | * this adapter. 710 | * 711 | * @param {string} deviceId - ID of the device 712 | */ 713 | handleDeviceSaved(deviceId) { 714 | this.savedDevices.add(deviceId); 715 | 716 | if (this.devices.hasOwnProperty(deviceId)) { 717 | this.devices[deviceId].startReading(true); 718 | } 719 | } 720 | 721 | /** 722 | * Remove a ThingURLDevice from the ThingURLAdapter. 723 | * 724 | * @param {Object} device The device to remove. 725 | * @param {boolean} internal Whether or not this is being called internally 726 | * @return {Promise} which resolves to the device removed. 727 | */ 728 | removeThing(device, internal) { 729 | return this.removeDeviceFromConfig(device).then(() => { 730 | if (!internal) { 731 | this.savedDevices.delete(device.id); 732 | } 733 | 734 | if (this.devices.hasOwnProperty(device.id)) { 735 | this.handleDeviceRemoved(device); 736 | device.closeWebSocket(); 737 | return device; 738 | } else { 739 | throw new Error(`Device: ${device.id} not found.`); 740 | } 741 | }); 742 | } 743 | 744 | /** 745 | * Remove a device's URL from this adapter's config if it was manually added. 746 | * 747 | * @param {Object} device The device to remove. 748 | */ 749 | async removeDeviceFromConfig(device) { 750 | try { 751 | const db = new Database(this.packageName); 752 | await db.open(); 753 | const config = await db.loadConfig(); 754 | 755 | // If the device's URL is saved in the config, remove it. 756 | const urlIndex = config.urls.findIndex((configInfo) => { 757 | return configInfo.href === device.url; 758 | }); 759 | if (urlIndex >= 0) { 760 | config.urls.splice(urlIndex, 1); 761 | await db.saveConfig(config); 762 | 763 | // Remove from list of known URLs as well. 764 | const adjustedUrl = device.url.replace(/\/$/, ''); 765 | if (this.knownUrls.hasOwnProperty(adjustedUrl)) { 766 | delete this.knownUrls[adjustedUrl]; 767 | } 768 | } 769 | } catch (err) { 770 | console.error(`Failed to remove device ${device.id} from config: ${err}`); 771 | } 772 | } 773 | 774 | startPairing() { 775 | for (const knownUrl of Object.values(this.knownUrls)) { 776 | this.loadThing(knownUrl).catch((err) => { 777 | console.warn(`Unable to reload Thing(s) from ${knownUrl}: ${err}`); 778 | }); 779 | } 780 | } 781 | 782 | unload() { 783 | if (webthingBrowser) { 784 | webthingBrowser.stop(); 785 | } 786 | 787 | if (subtypeBrowser) { 788 | subtypeBrowser.stop(); 789 | } 790 | 791 | if (httpBrowser) { 792 | httpBrowser.stop(); 793 | } 794 | 795 | for (const id in this.devices) { 796 | this.devices[id].closeWebSocket(); 797 | } 798 | 799 | return super.unload(); 800 | } 801 | } 802 | 803 | function startDNSDiscovery(adapter) { 804 | console.log('Starting mDNS discovery'); 805 | 806 | webthingBrowser = 807 | new dnssd.Browser(new dnssd.ServiceType('_webthing._tcp')); 808 | webthingBrowser.on('serviceUp', (service) => { 809 | const host = service.host.replace(/\.$/, ''); 810 | let protocol = 'http'; 811 | if (service.txt.hasOwnProperty('tls') && service.txt.tls === '1') { 812 | protocol = 'https'; 813 | } 814 | adapter.loadThing({ 815 | href: `${protocol}://${host}:${service.port}${service.txt.path}`, 816 | authentication: { 817 | method: 'none', 818 | }, 819 | }); 820 | }); 821 | webthingBrowser.on('serviceDown', (service) => { 822 | const host = service.host.replace(/\.$/, ''); 823 | let protocol = 'http'; 824 | if (service.txt.hasOwnProperty('tls') && service.txt.tls === '1') { 825 | protocol = 'https'; 826 | } 827 | adapter.unloadThing( 828 | `${protocol}://${host}:${service.port}${service.txt.path}` 829 | ); 830 | }); 831 | webthingBrowser.start(); 832 | 833 | // Support legacy devices 834 | subtypeBrowser = 835 | new dnssd.Browser(new dnssd.ServiceType('_http._tcp,_webthing')); 836 | subtypeBrowser.on('serviceUp', (service) => { 837 | adapter.loadThing({ 838 | href: service.txt.url, 839 | authentication: { 840 | method: 'none', 841 | }, 842 | }); 843 | }); 844 | subtypeBrowser.on('serviceDown', (service) => { 845 | adapter.unloadThing(service.txt.url); 846 | }); 847 | subtypeBrowser.start(); 848 | 849 | httpBrowser = new dnssd.Browser(new dnssd.ServiceType('_http._tcp')); 850 | httpBrowser.on('serviceUp', (service) => { 851 | if (typeof service.txt === 'object' && 852 | service.txt.hasOwnProperty('webthing')) { 853 | adapter.loadThing({ 854 | href: service.txt.url, 855 | authentication: { 856 | method: 'none', 857 | }, 858 | }); 859 | } 860 | }); 861 | httpBrowser.on('serviceDown', (service) => { 862 | if (typeof service.txt === 'object' && 863 | service.txt.hasOwnProperty('webthing')) { 864 | adapter.unloadThing(service.txt.url); 865 | } 866 | }); 867 | httpBrowser.start(); 868 | } 869 | 870 | function loadThingURLAdapter(addonManager) { 871 | const adapter = new ThingURLAdapter(addonManager); 872 | 873 | const db = new Database(manifest.id); 874 | db.open().then(() => { 875 | return db.loadConfig(); 876 | }).then((config) => { 877 | if (typeof config.pollInterval === 'number') { 878 | adapter.pollInterval = config.pollInterval * 1000; 879 | } 880 | 881 | // Transition from old config format 882 | let modified = false; 883 | const urls = []; 884 | for (const entry of config.urls) { 885 | if (typeof entry === 'string') { 886 | urls.push({ 887 | href: entry, 888 | authentication: { 889 | method: 'none', 890 | }, 891 | }); 892 | 893 | modified = true; 894 | } else { 895 | urls.push(entry); 896 | } 897 | } 898 | 899 | if (modified) { 900 | config.urls = urls; 901 | db.saveConfig(config); 902 | } 903 | 904 | for (const url of config.urls) { 905 | adapter.loadThing(url); 906 | } 907 | 908 | startDNSDiscovery(adapter); 909 | }).catch(console.error); 910 | } 911 | 912 | module.exports = loadThingURLAdapter; 913 | --------------------------------------------------------------------------------