diff --git a/niceday-api/index.js b/niceday-api/index.js index 35a39b6..ed4e8b0 100644 --- a/niceday-api/index.js +++ b/niceday-api/index.js @@ -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'); @@ -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 = { @@ -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) { + // 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}`); diff --git a/niceday-api/index.test.js b/niceday-api/index.test.js index fda05c2..4469ba8 100644 --- a/niceday-api/index.test.js +++ b/niceday-api/index.test.js @@ -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 } } } }]; @@ -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); diff --git a/niceday-api/login.mjs b/niceday-api/login.mjs index 71dd8d7..cf8d633 100644 --- a/niceday-api/login.mjs +++ b/niceday-api/login.mjs @@ -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) diff --git a/niceday-api/service/MessagesService.js b/niceday-api/service/MessagesService.js index 9d95cf2..8e0eec6 100644 --- a/niceday-api/service/MessagesService.js +++ b/niceday-api/service/MessagesService.js @@ -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 * @@ -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)); }); };