Skip to content

Add basic extension add-on framework. #2155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"express-ws": "^4.0.0",
"find": "^0.3.0",
"gateway-addon": "https://github.com/mozilla-iot/gateway-addon-node",
"glob-to-regexp": "^0.4.1",
"http-proxy": "^1.17.0",
"ip-regex": "^4.1.0",
"jsonwebtoken": "^8.5.1",
Expand Down
37 changes: 37 additions & 0 deletions src/addon-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class AddonManager extends EventEmitter {
this.notifiers = new Map();
this.devices = {};
this.outlets = {};
this.extensions = {};
this.deferredAdd = null;
this.deferredRemove = null;
this.addonsLoaded = false;
Expand Down Expand Up @@ -226,6 +227,27 @@ class AddonManager extends EventEmitter {
(n) => n.getPackageName() === packageId);
}

/**
* @method getExtensions
* @returns Returns a Map of the loaded extensions. The dictionary
* key corresponds to the extension ID.
*/
getExtensions() {
return this.extensions;
}

/**
* @method getExtensionsByPackageId
* @returns Returns a Map of loaded extensions with the given package ID.
*/
getExtensionsByPackageId(packageId) {
if (this.extensions.hasOwnProperty(packageId)) {
return this.extensions[packageId];
}

return {};
}

/**
* @method getDevice
* @returns Returns the device with the indicated id.
Expand Down Expand Up @@ -602,6 +624,17 @@ class AddonManager extends EventEmitter {
throw new Error(`Add-on not enabled: ${manifest.id}`);
}

if (manifest.content_scripts && manifest.web_accessible_resources) {
this.extensions[manifest.id] = {
extensions: manifest.content_scripts,
resources: manifest.web_accessible_resources,
};
}

if (!manifest.exec && config.get('ipc.protocol') !== 'inproc') {
return;
}

const errorCallback = (packageId, err) => {
console.error(`Failed to load add-on ${packageId}:`, err);
};
Expand Down Expand Up @@ -843,6 +876,10 @@ class AddonManager extends EventEmitter {
return Promise.resolve();
}

if (this.extensions.hasOwnProperty(packageId)) {
delete this.extensions[packageId];
}

const plugin = this.getPlugin(packageId);
let pluginProcess = {};
if (plugin) {
Expand Down
10 changes: 7 additions & 3 deletions src/addon-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,11 @@ function validateManifestJson(manifest) {
version: '',
};

if (config.get('ipc.protocol') !== 'inproc') {
// If we're not using in-process plugins, then we also need the exec
// keyword to exist.
if (config.get('ipc.protocol') !== 'inproc' &&
// eslint-disable-next-line max-len
manifest.gateway_specific_settings.webthings.primary_type !== 'extension') {
// If we're not using in-process plugins, and this is not an extension,
// then we also need the exec keyword to exist.
manifestTemplate.gateway_specific_settings.webthings.exec = '';
}

Expand Down Expand Up @@ -429,6 +431,8 @@ function loadManifestJson(packageId) {
version: manifest.version,
primary_type: manifest.gateway_specific_settings.webthings.primary_type,
exec: manifest.gateway_specific_settings.webthings.exec,
content_scripts: manifest.content_scripts,
web_accessible_resources: manifest.web_accessible_resources,
enabled: false,
};

Expand Down
1 change: 1 addition & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ exports.LOGS_PATH = '/logs';
exports.PUSH_PATH = '/push';
exports.PING_PATH = '/ping';
exports.PROXY_PATH = '/proxy';
exports.EXTENSIONS_PATH = '/extensions';
// Remember we end up in the build/* directory so these paths looks slightly
// different than you might expect.
exports.STATIC_PATH = path.join(__dirname, '../static');
Expand Down
61 changes: 61 additions & 0 deletions src/controllers/extensions_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

const AddonManager = require('../addon-manager');
const UserProfile = require('../user-profile');
const express = require('express');
const fs = require('fs');
const globToRegExp = require('glob-to-regexp');
const jwtMiddleware = require('../jwt-middleware');
const path = require('path');

const auth = jwtMiddleware.middleware();
const ExtensionsController = express.Router();

ExtensionsController.get('/', auth, (request, response) => {
const map = {};
for (const [key, value] of Object.entries(AddonManager.getExtensions())) {
map[key] = value.extensions;
}
response.status(200).json(map);
});

ExtensionsController.get('/:extensionId/*', (request, response) => {
const extensionId = request.params.extensionId;
const relPath = request.path.split('/').slice(2).join('/');

// make sure the extension is installed and enabled
const extensions = AddonManager.getExtensions();
if (!extensions.hasOwnProperty(extensionId)) {
response.status(404).send();
return;
}

// make sure the requested resource is listed in the extension's
// web_accessible_resources array
let matched = false;
const resources = extensions[extensionId].resources;
for (let resource of resources) {
resource = globToRegExp(resource);
if (resource.test(relPath)) {
matched = true;
break;
}
}

if (!matched) {
response.status(404).send();
return;
}

// make sure the file actually exists
const fullPath = path.join(UserProfile.addonsDir, extensionId, relPath);
if (!fs.existsSync(fullPath)) {
response.status(404).send();
return;
}

// finally, send the file
response.sendFile(fullPath);
});

module.exports = ExtensionsController;
2 changes: 2 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ const Router = {
// First look for a static file
const staticHandler = express.static(Constants.BUILD_STATIC_PATH);
app.use(Constants.UPLOADS_PATH, express.static(UserProfile.uploadsDir));
app.use(Constants.EXTENSIONS_PATH, nocache,
require('./controllers/extensions_controller'));
app.use((request, response, next) => {
if (request.path === '/' && request.accepts('html')) {
// We need this to hit RootController.
Expand Down
4 changes: 4 additions & 0 deletions static/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@ h1, h2, h3, h4, h5, h6 {
z-index: 0;
}

#menu-button.menu-shown {
z-index: 1000;
}

#menu-button {
background: no-repeat center/100% url('../optimized-images/menu.svg');
}
Expand Down
2 changes: 2 additions & 0 deletions static/css/menu.css
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
background-color: #5288af;
margin: 0;
transition: transform 0.25s ease;
z-index: 1000;
}

#main-menu.hidden {
Expand Down Expand Up @@ -105,6 +106,7 @@
height: 100%;
width: 100%;
animation: show-scrim 0.25s ease 0s;
z-index: 999;
}

#menu-scrim.hidden {
Expand Down
9 changes: 9 additions & 0 deletions static/js/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,17 @@ const API = {
return res.json();
});
},

getExtensions: function() {
return fetch('/extensions', {
headers: this.headers(),
}).then((res) => {
return res.json();
});
},
};

// Elevate this to the window level.
window.API = API;

module.exports = API;
74 changes: 68 additions & 6 deletions static/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ let LogsScreen;
// eslint-disable-next-line prefer-const
let Speech;

const page = require('page');
const shaka = require('shaka-player/dist/shaka-player.compiled');
const MobileDragDrop = require('mobile-drag-drop/index.min');
const ScrollBehavior = require('mobile-drag-drop/scroll-behaviour.min');
Expand Down Expand Up @@ -115,7 +116,7 @@ const App = {
this.views.rule = document.getElementById('rule-view');
this.views.assistant = document.getElementById('assistant-view');
this.views.logs = document.getElementById('logs-view');
this.currentView = 'things';
this.currentView = this.views.things;
this.menuButton = document.getElementById('menu-button');
this.menuButton.addEventListener('click', Menu.toggle.bind(Menu));
this.overflowButton = document.getElementById('overflow-button');
Expand All @@ -137,8 +138,36 @@ const App = {
this.wsBackoff = 1000;
this.initWebSocket();

this.extensions = {};

Menu.init();
Router.init();

API.getExtensions().then((extensions) => {
for (const [key, value] of Object.entries(extensions)) {
for (const extension of value) {
if (extension.css) {
for (const path of extension.css) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = `/extensions/${encodeURIComponent(key)}/${path}`;

document.head.appendChild(link);
}
}

if (extension.js) {
for (const path of extension.js) {
const script = document.createElement('script');
script.src = `/extensions/${encodeURIComponent(key)}/${path}`;

document.head.appendChild(script);
}
}
}
}
});
},

initWebSocket() {
Expand Down Expand Up @@ -270,15 +299,46 @@ const App = {
this.selectView('logs');
},

registerExtension: function(extension) {
this.extensions[extension.id] = extension;
},

showExtension: function(context) {
const extensionId = context.params.extensionId;

if (this.extensions.hasOwnProperty(extensionId)) {
this.extensions[extensionId].show();
this.selectView(
`extension-${Utils.escapeHtmlForIdClass(extensionId)}-view`
);
} else {
console.warn('Unknown extension:', extensionId);
page('/things');
}
},

selectView: function(view) {
if (!this.views[view]) {
console.error('Tried to select view that didnt exist');
let el = null;
if (view.startsWith('extension-')) {
// load extensions at runtime
el = document.getElementById(view);
} else {
el = this.views[view];
}

if (!el) {
console.error('Tried to select view that didn\'t exist:', view);
return;
}
this.views[this.currentView].classList.remove('selected');
this.views[view].classList.add('selected');

this.currentView.classList.add('hidden');
this.currentView.classList.remove('selected');

el.classList.remove('hidden');
el.classList.add('selected');

Menu.selectItem(view);
this.currentView = view;
this.currentView = el;
},

showMenuButton: function() {
Expand Down Expand Up @@ -452,6 +512,8 @@ require('./components/property/temperature');
require('./components/property/video');
require('./components/property/voltage');

require('./extension');

if (navigator.serviceWorker) {
navigator.serviceWorker.register('/service-worker.js', {
scope: '/',
Expand Down
41 changes: 41 additions & 0 deletions static/js/extension.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Extension add-on class.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';

const App = require('./app');
const Menu = require('./views/menu');

class Extension {
constructor(id) {
this.id = id;
App.registerExtension(this);
}

/**
* Add a new top-level menu entry.
*
* @param {string} name - The name to insert into the menu.
*
* @returns {Node} Node object which the extension can draw content to.
*/
addMenuEntry(name) {
return Menu.addExtensionItem(this.id, name);
}

/**
* Show the extension content.
*/
show() {
console.log(`Extension ${this.id} is being shown.`);
}
}

// Elevate this to the window level.
window.Extension = Extension;

module.exports = Extension;
1 change: 1 addition & 0 deletions static/js/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const Router = {
page('/rules/:rule', App.showRule.bind(App));
page('/logs', App.showLogs.bind(App));
page('/logs/things/:thingId/properties/:propId', App.showLogs.bind(App));
page('/extensions/:extensionId', App.showExtension.bind(App));
page();
},
};
Expand Down
Loading