Skip to content

Commit

Permalink
ewelink: adapting server
Browse files Browse the repository at this point in the history
  • Loading branch information
atrovato committed Dec 1, 2023
1 parent 0adff6c commit 0a202c2
Show file tree
Hide file tree
Showing 47 changed files with 1,265 additions and 1,848 deletions.
96 changes: 89 additions & 7 deletions server/services/ewelink/api/ewelink.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,79 @@ const asyncMiddleware = require('../../../api/middlewares/asyncMiddleware');

module.exports = function EwelinkController(eweLinkHandler) {
/**
* @api {post} /api/v1/service/ewelink/connect Connect to eWeLink cloud account.
* @apiName save
* @api {get} /api/v1/service/ewelink/config Get eWeLink application configuration.
* @apiName getConfig
* @apiGroup Ewelink
*/
async function connect(req, res) {
await eweLinkHandler.connect();
function getConfig(req, res) {
const { applicationId, applicationSecret, applicationRegion } = eweLinkHandler.configuration;
res.json({
success: true,
application_id: applicationId,
application_secret: applicationSecret,
application_region: applicationRegion,
});
}

/**
* @api {post} /api/v1/service/ewelink/config Save eWeLink application configuration.
* @apiName saveConfig
* @apiGroup Ewelink
*/
async function saveConfig(req, res) {
const {
application_id: applicationId,
application_secret: applicationSecret,
application_region: applicationRegion,
} = req.body;

await eweLinkHandler.saveConfiguration({
applicationId,
applicationSecret,
applicationRegion,
});

getConfig(req, res);
}

/**
* @api {get} /api/v1/service/ewelink/loginUrl Gets the eWelink login URL.
* @apiName loginUrl
* @apiGroup Ewelink
*/
async function loginUrl(req, res) {
const { redirect_url: redirectUrl } = req.query;
const ewelinkLoginUrl = await eweLinkHandler.buildLoginUrl({
redirectUrl,
});
res.json({ loginUrl: ewelinkLoginUrl });
}

/**
* @api {post} /api/v1/service/ewelink/token Generates a user token.
* @apiName exchangeToken
* @apiGroup Ewelink
*/
async function exchangeToken(req, res) {
const { redirect_url: redirectUrl, code, region, state } = req.body;
await eweLinkHandler.exchangeToken({
redirectUrl,
code,
region,
state,
});
res.json({ success: true });
}

/**
* @api {delete} /api/v1/service/ewelink/token Delete stored tokens and logout user.
* @apiName deleteToken
* @apiGroup Ewelink
*/
async function deleteToken(req, res) {
await eweLinkHandler.deleteToken();
res.json({ success: true });
}

/**
* @api {get} /api/v1/service/ewelink/status Get eWeLink connection status.
* @apiName status
Expand All @@ -34,10 +96,30 @@ module.exports = function EwelinkController(eweLinkHandler) {
}

return {
'post /api/v1/service/ewelink/connect': {
'get /api/v1/service/ewelink/config': {
authenticated: true,
admin: true,
controller: asyncMiddleware(getConfig),
},
'post /api/v1/service/ewelink/config': {
authenticated: true,
admin: true,
controller: asyncMiddleware(saveConfig),
},
'get /api/v1/service/ewelink/loginUrl': {
authenticated: true,
admin: true,
controller: asyncMiddleware(loginUrl),
},
'post /api/v1/service/ewelink/token': {
authenticated: true,
admin: true,
controller: asyncMiddleware(exchangeToken),
},
'delete /api/v1/service/ewelink/token': {
authenticated: true,
admin: true,
controller: asyncMiddleware(connect),
controller: asyncMiddleware(deleteToken),
},
'get /api/v1/service/ewelink/status': {
authenticated: true,
Expand Down
8 changes: 4 additions & 4 deletions server/services/ewelink/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const logger = require('../../utils/logger');
const EweLinkHandler = require('./lib/device');
const EweLinkHandler = require('./lib');
const EwelinkController = require('./api/ewelink.controller');

module.exports = function EwelinkService(gladys, serviceId) {
// require the eWeLink module
const eWeLinkApi = require('ewelink-api');
const eWeLinkHandler = new EweLinkHandler(gladys, eWeLinkApi, serviceId);
const { default: eweLinkApi } = require('ewelink-api-next');
const eWeLinkHandler = new EweLinkHandler(gladys, eweLinkApi, serviceId);

/**
* @public
Expand All @@ -15,7 +15,7 @@ module.exports = function EwelinkService(gladys, serviceId) {
*/
async function start() {
logger.info('Starting eWeLink service');
await eWeLinkHandler.connect();
await eWeLinkHandler.loadConfiguration();
}

/**
Expand Down
18 changes: 18 additions & 0 deletions server/services/ewelink/lib/config/ewelink.createClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @description Create eWeLink client.
* @example
* this.createClient();
*/
async function createClient() {
const { applicationId, applicationSecret, applicationRegion } = this.configuration;

this.ewelinkClient = new this.eweLinkApi.WebAPI({
appId: applicationId,
appSecret: applicationSecret,
region: applicationRegion,
});
}

module.exports = {
createClient,
};
53 changes: 53 additions & 0 deletions server/services/ewelink/lib/config/ewelink.loadConfiguration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const { ServiceNotConfiguredError } = require('../../../../utils/coreErrors');
const logger = require('../../../../utils/logger');
const { CONFIGURATION_KEYS } = require('../utils/constants');

/**
* @description Load eWeLink configuration.
* @example
* await this.loadConfiguration();
*/
async function loadConfiguration() {
logger.info('eWeLink: loading stored configuration...');
this.updateStatus({ configured: false });

try {
const applicationId = await this.gladys.variable.getValue(CONFIGURATION_KEYS.APPLICATION_ID, this.serviceId);
const applicationSecret = await this.gladys.variable.getValue(
CONFIGURATION_KEYS.APPLICATION_SECRET,
this.serviceId,
);
const applicationRegion = await this.gladys.variable.getValue(
CONFIGURATION_KEYS.APPLICATION_REGION,
this.serviceId,
);

if (!applicationId || !applicationSecret || !applicationRegion) {
throw new ServiceNotConfiguredError('eWeLink configuration is not setup');
}

this.configuration = { applicationId, applicationSecret, applicationRegion };

this.createClient();

// Load tokens from databate
const tokens = await this.gladys.variable.getValue(CONFIGURATION_KEYS.USER_TOKENS, this.serviceId);
if (tokens) {
const tokenObject = JSON.parse(tokens);
this.ewelinkClient.at = tokenObject.accessToken;
this.ewelinkClient.rt = tokenObject.refreshToken;
} else {
throw new ServiceNotConfiguredError('eWeLink user is not connected');
}

this.updateStatus({ configured: true, connected: !!tokens });
logger.info('eWeLink: stored configuration well loaded...');
} catch (e) {
this.updateStatus({ configured: false, connected: false });
throw e;
}
}

module.exports = {
loadConfiguration,
};
42 changes: 42 additions & 0 deletions server/services/ewelink/lib/config/ewelink.saveConfiguration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const { BadParameters } = require('../../../../utils/coreErrors');
const logger = require('../../../../utils/logger');
const { CONFIGURATION_KEYS } = require('../utils/constants');

/**
* @description Save eWeLink application configuration.
* @param {object} configuration - EWeLink application configuration.
* @param {string} [configuration.applicationId] - Application ID.
* @param {string} [configuration.applicationSecret] - Application secret.
* @param {string} [configuration.applicationRegion] - Application region.
* @example
* await this.saveConfiguration(configuration);
*/
async function saveConfiguration({ applicationId = '', applicationSecret = '', applicationRegion = '' }) {
logger.info('eWeLink: saving new configuration...');
this.updateStatus({ configured: false });

if (applicationId === '' || applicationSecret === '' || applicationRegion === '') {
throw new BadParameters('eWeLink: all application ID/Secret/Region are required.');
}

try {
await this.gladys.variable.setValue(CONFIGURATION_KEYS.APPLICATION_ID, applicationId, this.serviceId);
await this.gladys.variable.setValue(CONFIGURATION_KEYS.APPLICATION_SECRET, applicationSecret, this.serviceId);
await this.gladys.variable.setValue(CONFIGURATION_KEYS.APPLICATION_REGION, applicationRegion, this.serviceId);
await this.gladys.variable.destroy(CONFIGURATION_KEYS.USER_TOKENS, this.serviceId);

this.configuration = { applicationId, applicationSecret, applicationRegion };

this.createClient();

this.updateStatus({ configured: true, connected: false });
logger.info('eWeLink: new configuration well saved...');
} catch (e) {
this.updateStatus({ configured: false });
throw e;
}
}

module.exports = {
saveConfiguration,
};
20 changes: 20 additions & 0 deletions server/services/ewelink/lib/config/ewelink.updateStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const { EVENTS, WEBSOCKET_MESSAGE_TYPES } = require('../../../../utils/constants');

/**
* @description Update the service status and emit WebSocket event.
* @param {object} newStatus - New service status.
* @example
* this.updateStatus({ configured: true });
*/
function updateStatus(newStatus) {
this.status = { ...this.status, ...newStatus };

this.gladys.event.emit(EVENTS.WEBSOCKET.SEND_ALL, {
type: WEBSOCKET_MESSAGE_TYPES.EWELINK.STATUS,
payload: this.status,
});
}

module.exports = {
updateStatus,
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@
* @description Get eWeLink status.
* @returns {object} Current eWeLink network status.
* @example
* status();
* this.status();
*/
function status() {
const eweLinkStatus = {
configured: this.configured,
connected: this.connected,
};
return eweLinkStatus;
return this.status;
}

module.exports = {
Expand Down
56 changes: 0 additions & 56 deletions server/services/ewelink/lib/device/connect.js

This file was deleted.

Loading

0 comments on commit 0a202c2

Please sign in to comment.