Skip to content

Commit

Permalink
ewelink: rename Client to WebAPIClient
Browse files Browse the repository at this point in the history
  • Loading branch information
atrovato committed Dec 10, 2023
1 parent 15fd09a commit 8888188
Show file tree
Hide file tree
Showing 20 changed files with 59 additions and 57 deletions.
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
/**
* @description Create eWeLink client.
* @description Create eWeLink Web API and WebSocket clients.
* @example
* this.createClient();
* await this.createClients();
*/
async function createClient() {
async function createClients() {
const { applicationId, applicationSecret, applicationRegion } = this.configuration;

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

module.exports = {
createClient,
createClients,
};
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function loadConfiguration() {

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

this.createClient();
this.createClients();
} catch (e) {
this.updateStatus({ configured: false, connected: false });
throw e;
Expand All @@ -42,8 +42,8 @@ async function loadConfiguration() {
}

const tokenObject = JSON.parse(tokens);
this.ewelinkClient.at = tokenObject.accessToken;
this.ewelinkClient.rt = tokenObject.refreshToken;
this.ewelinkWebAPIClient.at = tokenObject.accessToken;
this.ewelinkWebAPIClient.rt = tokenObject.refreshToken;

logger.info('eWeLink: stored configuration well loaded...');
} catch (e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function saveConfiguration({ applicationId = '', applicationSecret = '', a

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

this.createClient();
this.createClients();

this.updateStatus({ configured: true, connected: false });
logger.info('eWeLink: new configuration well saved...');
Expand Down
4 changes: 3 additions & 1 deletion server/services/ewelink/lib/device/discover.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ const { getExternalId } = require('../utils/externalId');
* discover();
*/
async function discover() {
const { thingList = [] } = await this.handleRequest(async () => this.ewelinkClient.device.getAllThingsAllPages());
const { thingList = [] } = await this.handleRequest(async () =>
this.ewelinkWebAPIClient.device.getAllThingsAllPages(),
);
logger.info(`eWeLink: ${thingList.length} device(s) found while retrieving from the cloud !`);

const discoveredDevices = [];
Expand Down
2 changes: 1 addition & 1 deletion server/services/ewelink/lib/device/poll.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async function poll(device) {

try {
const { thingList } = await this.handleRequest(async () =>
this.ewelinkClient.device.getThings({ thingList: [{ id: deviceId }] }),
this.ewelinkWebAPIClient.device.getThings({ thingList: [{ id: deviceId }] }),
);
const [{ itemData: eWeLinkDevice }] = thingList;
logger.debug('eWeLink: load device: %j', eWeLinkDevice);
Expand Down
2 changes: 1 addition & 1 deletion server/services/ewelink/lib/device/setValue.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async function setValue(device, deviceFeature, value) {
params.switch = binaryValue;
}

await this.handleRequest(async () => this.ewelinkClient.device.setThingStatus(1, deviceId, params));
await this.handleRequest(async () => this.ewelinkWebAPIClient.device.setThingStatus(1, deviceId, params));
break;
}
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async function handleRequest(request, nbRetry = 0) {
// 402 - Access token expired, so refresh it and retry.
// see https://coolkit-technologies.github.io/eWeLink-API/#/en/APICenterV2?id=error-codes
if (response.error === 402 && nbRetry < NB_MAX_RETRY_EXPIRED) {
const tokenResponse = await this.ewelinkClient.user.refreshToken();
const tokenResponse = await this.ewelinkWebAPIClient.user.refreshToken();
const tokens = await this.handleResponse(tokenResponse);
// Store new tokens
await this.saveTokens(tokens);
Expand Down
6 changes: 3 additions & 3 deletions server/services/ewelink/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const { updateStatus } = require('./config/ewelink.updateStatus');
const { getStatus } = require('./config/ewelink.getStatus');
const { saveConfiguration } = require('./config/ewelink.saveConfiguration');
const { loadConfiguration } = require('./config/ewelink.loadConfiguration');
const { createClient } = require('./config/ewelink.createClient');
const { createClients } = require('./config/ewelink.createClients');

const { buildLoginUrl } = require('./user/ewelink.buildLoginUrl');
const { exchangeToken } = require('./user/ewelink.exchangeToken');
Expand All @@ -33,7 +33,7 @@ const EweLinkHandler = function EweLinkHandler(gladys, eweLinkApi, serviceId) {
this.eweLinkApi = eweLinkApi;
this.serviceId = serviceId;

this.ewelinkClient = null;
this.ewelinkWebAPIClient = null;
this.loginState = null;
this.configuration = {};
this.status = {
Expand All @@ -46,7 +46,7 @@ EweLinkHandler.prototype.updateStatus = updateStatus;

EweLinkHandler.prototype.saveConfiguration = saveConfiguration;
EweLinkHandler.prototype.loadConfiguration = loadConfiguration;
EweLinkHandler.prototype.createClient = createClient;
EweLinkHandler.prototype.createClients = createClients;

EweLinkHandler.prototype.buildLoginUrl = buildLoginUrl;
EweLinkHandler.prototype.exchangeToken = exchangeToken;
Expand Down
2 changes: 1 addition & 1 deletion server/services/ewelink/lib/user/ewelink.buildLoginUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function buildLoginUrl({ redirectUrl }) {
logger.info('eWeLink: create new login URL');
const state = generate(10, { number: true, lowercase: true, uppercase: true });
this.loginState = state;
return this.ewelinkClient.oauth.createLoginUrl({
return this.ewelinkWebAPIClient.oauth.createLoginUrl({
redirectUrl,
grantType: 'authorization_code',
state,
Expand Down
10 changes: 5 additions & 5 deletions server/services/ewelink/lib/user/ewelink.deleteTokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ async function deleteTokens() {
logger.info('eWeLink: disconnecting user...');
// see https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0?id=unbind-third-party-accounts
const logoutCall = async () =>
this.ewelinkClient.request.delete('/v2/user/oauth/token', {
this.ewelinkWebAPIClient.request.delete('/v2/user/oauth/token', {
headers: {
'X-CK-Appid': this.ewelinkClient.appId || '',
Authorization: `Bearer ${this.ewelinkClient.at}`,
'X-CK-Appid': this.ewelinkWebAPIClient.appId || '',
Authorization: `Bearer ${this.ewelinkWebAPIClient.at}`,
},
});

await this.handleRequest(logoutCall);

// Clear tokens
await this.gladys.variable.destroy(CONFIGURATION_KEYS.USER_TOKENS, this.serviceId);
this.ewelinkClient.at = null;
this.ewelinkClient.rt = null;
this.ewelinkWebAPIClient.at = null;
this.ewelinkWebAPIClient.rt = null;

this.updateStatus({ connected: false });
logger.info('eWeLink: user well disconnected');
Expand Down
6 changes: 3 additions & 3 deletions server/services/ewelink/lib/user/ewelink.exchangeToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ async function exchangeToken({ redirectUrl, code, region, state }) {
throw new BadParameters('eWeLink login state is invalid');
}

const tokenResponse = await this.ewelinkClient.oauth.getToken({
const tokenResponse = await this.ewelinkWebAPIClient.oauth.getToken({
region,
redirectUrl,
code,
});

const data = await this.handleResponse(tokenResponse);

this.ewelinkClient.at = data.accessToken;
this.ewelinkClient.rt = data.refreshToken;
this.ewelinkWebAPIClient.at = data.accessToken;
this.ewelinkWebAPIClient.rt = data.refreshToken;

await this.saveTokens(data);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ describe('eWeLinkHandler loadConfiguration', () => {
region: 'APPLICATION_REGION_VALUE',
});

expect(eWeLinkHandler.ewelinkClient.at).eq('ACCESS_TOKEN');
expect(eWeLinkHandler.ewelinkClient.rt).eq('REFRESH_TOKEN');
expect(eWeLinkHandler.ewelinkWebAPIClient.at).eq('ACCESS_TOKEN');
expect(eWeLinkHandler.ewelinkWebAPIClient.rt).eq('REFRESH_TOKEN');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('eWeLinkHandler saveConfiguration', () => {
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);

expect(eWeLinkHandler.ewelinkClient).eq(null);
expect(eWeLinkHandler.ewelinkWebAPIClient).eq(null);
});

it('should throw a BadParameter error as SECRET and REGION variables are mossing', async () => {
Expand All @@ -63,7 +63,7 @@ describe('eWeLinkHandler saveConfiguration', () => {
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);

expect(eWeLinkHandler.ewelinkClient).eq(null);
expect(eWeLinkHandler.ewelinkWebAPIClient).eq(null);
});

it('should throw a BadParameter error as REGION variables is missing', async () => {
Expand All @@ -79,7 +79,7 @@ describe('eWeLinkHandler saveConfiguration', () => {
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);

expect(eWeLinkHandler.ewelinkClient).eq(null);
expect(eWeLinkHandler.ewelinkWebAPIClient).eq(null);
});

it('should throw a error on database store failure', async () => {
Expand All @@ -105,7 +105,7 @@ describe('eWeLinkHandler saveConfiguration', () => {
assert.calledOnceWithExactly(gladys.variable.setValue, 'APPLICATION_ID', EWELINK_APP_ID, SERVICE_ID);
assert.notCalled(gladys.variable.destroy);

expect(eWeLinkHandler.ewelinkClient).eq(null);
expect(eWeLinkHandler.ewelinkWebAPIClient).eq(null);
});

it('should save configuration and send events', async () => {
Expand All @@ -131,6 +131,6 @@ describe('eWeLinkHandler saveConfiguration', () => {
assert.calledWithExactly(gladys.variable.setValue, 'APPLICATION_REGION', EWELINK_APP_REGION, SERVICE_ID);
assert.calledOnceWithExactly(gladys.variable.destroy, 'USER_TOKENS', SERVICE_ID);

expect(eWeLinkHandler.ewelinkClient).not.eq(null);
expect(eWeLinkHandler.ewelinkWebAPIClient).not.eq(null);
});
});
8 changes: 4 additions & 4 deletions server/test/services/ewelink/lib/device/discover.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('EweLinkHandler discover', () => {

beforeEach(() => {
eWeLinkHandler = new EwelinkHandler(gladys, EweLinkApiMock, SERVICE_ID);
eWeLinkHandler.ewelinkClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.ewelinkWebAPIClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.status = { configured: true, connected: true };
});

Expand All @@ -54,12 +54,12 @@ describe('EweLinkHandler discover', () => {
});
it('should found 0 devices', async () => {
// Force eWeLink API to give empty response
sinon.stub(eWeLinkHandler.ewelinkClient.device, 'getAllThingsAllPages').resolves({ error: 0, data: {} });
sinon.stub(eWeLinkHandler.ewelinkWebAPIClient.device, 'getAllThingsAllPages').resolves({ error: 0, data: {} });
const newDevices = await eWeLinkHandler.discover();
expect(newDevices).to.have.deep.members([]);
});
it('should return not configured error', async () => {
eWeLinkHandler.ewelinkClient.at = EWELINK_INVALID_ACCESS_TOKEN;
eWeLinkHandler.ewelinkWebAPIClient.at = EWELINK_INVALID_ACCESS_TOKEN;
try {
await eWeLinkHandler.discover();
assert.fail();
Expand All @@ -69,7 +69,7 @@ describe('EweLinkHandler discover', () => {
}
});
it('should throw an error and emit a message when AccessToken is no more valid', async () => {
eWeLinkHandler.ewelinkClient.at = EWELINK_DENIED_ACCESS_TOKEN;
eWeLinkHandler.ewelinkWebAPIClient.at = EWELINK_DENIED_ACCESS_TOKEN;
try {
await eWeLinkHandler.discover();
assert.fail();
Expand Down
4 changes: 2 additions & 2 deletions server/test/services/ewelink/lib/device/poll.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('eWeLinkHandler poll', () => {
};

eWeLinkHandler = new EwelinkHandler(gladys, EweLinkApiMock, SERVICE_ID);
eWeLinkHandler.ewelinkClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.ewelinkWebAPIClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.status = { configured: true, connected: true };
});

Expand Down Expand Up @@ -93,7 +93,7 @@ describe('eWeLinkHandler poll', () => {
}
});
it('should throw an error when AccessToken is no more valid', async () => {
eWeLinkHandler.ewelinkClient.at = EWELINK_DENIED_ACCESS_TOKEN;
eWeLinkHandler.ewelinkWebAPIClient.at = EWELINK_DENIED_ACCESS_TOKEN;
try {
await eWeLinkHandler.poll(Gladys2ChDevice);
assert.fail();
Expand Down
4 changes: 2 additions & 2 deletions server/test/services/ewelink/lib/device/setValue.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('eWeLinkHandler setValue', () => {
beforeEach(() => {
const gladys = {};
eWeLinkHandler = new EwelinkHandler(gladys, EweLinkApiMock, SERVICE_ID);
eWeLinkHandler.ewelinkClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.ewelinkWebAPIClient = new EweLinkApiMock.WebAPI();
eWeLinkHandler.status = { configured: true, connected: true };
});

Expand Down Expand Up @@ -66,7 +66,7 @@ describe('eWeLinkHandler setValue', () => {
}
});
it('should throw an error when AccessToken is no more valid', async () => {
eWeLinkHandler.ewelinkClient.at = EWELINK_DENIED_ACCESS_TOKEN;
eWeLinkHandler.ewelinkWebAPIClient.at = EWELINK_DENIED_ACCESS_TOKEN;
try {
await eWeLinkHandler.setValue(
Gladys2ChDevice,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('eWeLinkHandler handleRequest', () => {

eWeLinkHandler = new EwelinkHandler(gladys, null, SERVICE_ID);
eWeLinkHandler.status = { configured: true, connected: true };
eWeLinkHandler.ewelinkClient = {
eWeLinkHandler.ewelinkWebAPIClient = {
user: {
refreshToken: stub().resolves({ error: 0, data: tokens }),
},
Expand All @@ -51,7 +51,7 @@ describe('eWeLinkHandler handleRequest', () => {
}

assert.notCalled(request);
assert.notCalled(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.notCalled(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);
assert.notCalled(gladys.event.emit);
Expand All @@ -70,7 +70,7 @@ describe('eWeLinkHandler handleRequest', () => {
}

assert.notCalled(request);
assert.notCalled(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.notCalled(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);
assert.notCalled(gladys.event.emit);
Expand All @@ -83,7 +83,7 @@ describe('eWeLinkHandler handleRequest', () => {
expect(result).eq('SUCCESS');

assert.calledOnceWithExactly(request);
assert.notCalled(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.notCalled(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);
assert.notCalled(gladys.event.emit);
Expand All @@ -100,7 +100,7 @@ describe('eWeLinkHandler handleRequest', () => {

assert.calledTwice(request);
assert.alwaysCalledWithExactly(request);
assert.calledOnce(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.calledOnce(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.calledOnceWithExactly(gladys.variable.setValue, 'USER_TOKENS', JSON.stringify(tokens), SERVICE_ID);
assert.notCalled(gladys.variable.destroy);
assert.notCalled(gladys.event.emit);
Expand All @@ -119,7 +119,7 @@ describe('eWeLinkHandler handleRequest', () => {

assert.calledTwice(request);
assert.alwaysCalledWithExactly(request);
assert.calledOnceWithExactly(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.calledOnceWithExactly(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.calledOnceWithExactly(gladys.variable.setValue, 'USER_TOKENS', JSON.stringify(tokens), SERVICE_ID);
assert.calledOnceWithExactly(gladys.variable.destroy, 'USER_TOKENS', SERVICE_ID);
assert.calledOnceWithExactly(gladys.event.emit, EVENTS.WEBSOCKET.SEND_ALL, {
Expand All @@ -129,7 +129,7 @@ describe('eWeLinkHandler handleRequest', () => {
});

it('should not retry if refresh token returns 402 error', async () => {
eWeLinkHandler.ewelinkClient.user.refreshToken = stub().resolves({ error: 402, msg: 'ERROR FROM API' });
eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken = stub().resolves({ error: 402, msg: 'ERROR FROM API' });

const request = stub().resolves({ data: 'RETRY', error: 402 });

Expand All @@ -142,7 +142,7 @@ describe('eWeLinkHandler handleRequest', () => {
}

assert.calledOnceWithExactly(request);
assert.calledOnceWithExactly(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.calledOnceWithExactly(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.notCalled(gladys.variable.setValue);
assert.calledOnceWithExactly(gladys.variable.destroy, 'USER_TOKENS', SERVICE_ID);
assert.calledOnceWithExactly(gladys.event.emit, EVENTS.WEBSOCKET.SEND_ALL, {
Expand All @@ -163,7 +163,7 @@ describe('eWeLinkHandler handleRequest', () => {
}

assert.calledOnceWithExactly(request);
assert.notCalled(eWeLinkHandler.ewelinkClient.user.refreshToken);
assert.notCalled(eWeLinkHandler.ewelinkWebAPIClient.user.refreshToken);
assert.notCalled(gladys.variable.setValue);
assert.notCalled(gladys.variable.destroy);
assert.notCalled(gladys.event.emit);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('eWeLinkHandler buildLoginUrl', () => {

beforeEach(() => {
eWeLinkHandler = new EwelinkHandler({}, null, SERVICE_ID);
eWeLinkHandler.ewelinkClient = {
eWeLinkHandler.ewelinkWebAPIClient = {
oauth: {
createLoginUrl: fake.returns('LOGIN_URL'),
},
Expand All @@ -28,9 +28,9 @@ describe('eWeLinkHandler buildLoginUrl', () => {
const redirectUrl = 'http://localhost:1440/redirectUrl';
const loginUrl = eWeLinkHandler.buildLoginUrl({ redirectUrl });

assert.calledOnce(eWeLinkHandler.ewelinkClient.oauth.createLoginUrl);
assert.calledOnce(eWeLinkHandler.ewelinkWebAPIClient.oauth.createLoginUrl);
assert.calledWithMatch(
eWeLinkHandler.ewelinkClient.oauth.createLoginUrl,
eWeLinkHandler.ewelinkWebAPIClient.oauth.createLoginUrl,
match({
redirectUrl,
grantType: 'authorization_code',
Expand Down
Loading

0 comments on commit 8888188

Please sign in to comment.