Skip to content
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

383 messages optimization #19

Merged
merged 3 commits into from
Jul 14, 2023
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
34 changes: 33 additions & 1 deletion niceday-api/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const { Authentication, SenseServer } = require('@sense-os/goalie-js');
const {
Authentication, SenseServer, Chat, ConnectionStatus, SenseServerEnvironment,
} = require('@sense-os/goalie-js');
const schedule = require('node-schedule');
const path = require('path');
const http = require('http');
Expand All @@ -12,14 +14,18 @@ const serverPort = 8080;

const { THERAPIST_PASSWORD, THERAPIST_EMAIL_ADDRESS, ENVIRONMENT } = process.env;
let selectedServer;
let selectedServerEnv;

if (ENVIRONMENT === 'dev') {
selectedServer = SenseServer.Alpha;
selectedServerEnv = SenseServerEnvironment.Alpha;
} else {
selectedServer = SenseServer.Production;
selectedServerEnv = SenseServerEnvironment.Production;
}

const authSdk = new Authentication(selectedServer);
const chatSdk = new Chat();

// swaggerRouter configuration
const options = {
Expand All @@ -31,11 +37,37 @@ const options = {
const expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, 'api/openapi.yaml'), options);
const app = expressAppConfig.getApp();

function setupChat(therapistId, token) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right... so, all this setup only needs to be done once (per session/token?). Before was it doing all this authentication stuff every time it sent a message?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, isn't this great?

// Setup connection
chatSdk.init(selectedServerEnv);
chatSdk.connect(therapistId, token);

// Send initial presence when connected
chatSdk.subscribeToConnectionStatusChanges((connectionStatus) => {
if (connectionStatus === ConnectionStatus.Connected) {
chatSdk.sendInitialPresence();
app.set('chatsdk', chatSdk);
} else if (connectionStatus === ConnectionStatus.Disconnected) {
authSdk.login(THERAPIST_EMAIL_ADDRESS, THERAPIST_PASSWORD)
.then((response) => {
chatSdk.connect(response.user.id, response.token)
.catch((connectionError) => {
throw Error(`Error during connection: ${connectionError}`);
});
})
.catch((error) => {
throw Error(`Error during relogin: ${error}`);
});
}
});
}

function createNicedayApiServer() {
authSdk.login(THERAPIST_EMAIL_ADDRESS, THERAPIST_PASSWORD)
.then((response) => {
app.set('therapistId', response.user.id);
app.set('token', response.token);
setupChat(response.user.id, response.token);
})
.catch((error) => {
throw Error(`Error during authentication: ${error}`);
Expand Down
21 changes: 21 additions & 0 deletions niceday-api/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ require('isomorphic-fetch');
const NICEDAY_TEST_SERVERPORT = 8080;
const NICEDAY_TEST_USER_ID = 38527;
const NICEDAY_TEST_TRACKER_RRULE = 'DTSTART:20210310T150000\nRRULE:FREQ=DAILY';
const MOCK_ID_FROM = 1;
const MOCK_ID_TO = 12345;
const MOCK_USER_DATA = {
id: NICEDAY_TEST_USER_ID,
userProfile: {
firstName: 'Mr Mock',
},
};
const MOCK_TEST_MESSAGE = 'Test message';
const MOCK_TRACKER_RESPONSE = { response: 'mock response' };
const MOCK_SMOKING_TRACKER_RESPONSE = [
{ value: { measures: { measureCigarettes: { sensorData: MOCK_TRACKER_RESPONSE } } } }];
Expand Down Expand Up @@ -45,6 +48,24 @@ describe('Tests on niceday-api server using mocked goalie-js', () => {
SenseServerEnvironment: () => ({
Alpha: undefined,
}),
Chat: jest.fn().mockImplementation(() => ({
init: jest.fn(),
connect: jest.fn(),
markMessageAsRead: jest.fn(),
subscribeToConnectionStatusChanges: jest.fn(),
sendInitialPresence: jest.fn(),
subscribeToIncomingMessage: (handler) => {
const mockTestMessage = {
from: MOCK_ID_FROM,
to: MOCK_ID_TO,
content: {
TEXT: MOCK_TEST_MESSAGE,
},
};

handler(mockTestMessage);
},
})),
Contacts: jest.fn().mockImplementation(() => ({
getConnectedContacts: () => new Promise((resolve) => {
resolve(MOCK_USER_DATA);
Expand Down
9 changes: 2 additions & 7 deletions niceday-api/login.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,8 @@
import { Authentication, SenseServer } from '@sense-os/goalie-js';
import 'isomorphic-fetch'

const { ENVIRONMENT } = process.env;
if (ENVIRONMENT == 'dev'){
const authSdk = new Authentication(SenseServer.Alpha);
}
else {
const authSdk = new Authentication(SenseServer.Production);
}
const authSdk = new Authentication(SenseServer.Alpha);


// Read in command line arguments
var args = process.argv.slice(2)
Expand Down
55 changes: 7 additions & 48 deletions niceday-api/service/MessagesService.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
const {
Authentication, Chat, SenseServer, SenseServerEnvironment, ConnectionStatus,
} = require('@sense-os/goalie-js');

const { ENVIRONMENT, THERAPIST_EMAIL_ADDRESS, THERAPIST_PASSWORD } = process.env;

let selectedServerEnv;
let selectedServer;

if (ENVIRONMENT === 'dev') {
selectedServerEnv = SenseServerEnvironment.Alpha;
selectedServer = SenseServer.Alpha;
} else {
selectedServerEnv = SenseServerEnvironment.Production;
selectedServer = SenseServer.Production;
}
const authSdk = new Authentication(selectedServer);
/**
* Send a text message
*
Expand All @@ -23,38 +6,14 @@ const authSdk = new Authentication(selectedServer);
*
* no response value expected for this operation
* */

exports.sendTextMessage = function (req, body) {
return new Promise((resolve, reject) => {
const chatSdk = new Chat();
chatSdk.init(selectedServerEnv);
chatSdk.connect(req.app.get('therapistId'), req.app.get('token'))
.catch(() => {
// if the connection fails, we regenreate the token by logging in again
// and we try to reconnect
authSdk.login(THERAPIST_EMAIL_ADDRESS, THERAPIST_PASSWORD)
.then((response) => {
req.app.set('therapistId', response.user.id);
req.app.set('token', response.token);
chatSdk.connect(response.user.id, response.token)
.catch((connectError) => {
throw Error(`Error during chat connection: ${connectError}`);
});
})
.catch((loginError) => {
throw Error(`Error during authentication: ${loginError}`);
});
});

const subscriptionId = chatSdk.subscribeToConnectionStatusChanges((connectionStatus) => {
if (connectionStatus === ConnectionStatus.Connected) {
chatSdk.sendInitialPresence();
chatSdk.sendTextMessage(body.recipient_id, body.text).then((response) => {
console.log('Successfully sent the message', response);
chatSdk.unsubscribeFromConnectionStatusChanges(subscriptionId);
resolve();
})
.catch((error) => reject(error));
}
});
const chatSdk = req.app.get('chatsdk');
chatSdk.sendTextMessage(body.recipient_id, body.text).then((response) => {
console.log('Successfully sent the message', response);
resolve();
})
.catch((error) => reject(error));
});
};