robbie-sdk
Version:
Robbie Visio SDK to send events for analaysis
100 lines (91 loc) • 3.33 kB
JavaScript
export const CREATE_SESSION_ROUTE = 'rtc/create/';
export const REQUEST_EMOTIONS_ROUTE = 'rtc/ingest/';
export const CLOSE_SESSION_ROUTE = 'close/';
export const CONTENT_SOURCE_SDK = 'SDK'; // Content source 2 = API
export default class RobbieApi {
constructor(token, properties) {
if (token === undefined || token === '') {
throw new Error('Cannot connect to Robbie API without a token');
}
this._token = token;
this._properties = Object.assign({}, properties);
}
set properties(properties) {
this._properties = properties;
}
get properties() {
return this._properties;
}
static get baseUrl() {
if (process.env.NODE_ENV === 'production') {
return 'https://visio.robbieapis.com/sdk/web/v1/';
} else if (process.env.NODE_ENV === 'development') {
return 'http://localhost:8888/sdk/web/v1/';
} else if (process.env.NODE_ENV === 'staging') {
return 'https://visio-staging.robbieapis.com/sdk/web/v1/';
}
return 'http://localhost:8888/sdk/web/v1/';
}
/**
* Checks wether the class has been provided with a token
* @returns {boolean}
*/
_containsToken() {
return this._token != null && this._token !== '';
}
requestNewSession() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', RobbieApi.baseUrl + CREATE_SESSION_ROUTE);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Robbie-Sdk-Web-X-Token', `${this._token}`);
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 201) {
const response = JSON.parse(xhr.responseText);
resolve(response);
} else if (xhr.readyState === XMLHttpRequest.DONE) {
reject(xhr);
}
};
xhr.onerror = () => { reject(xhr); };
xhr.ontimeout = () => { reject(new Error('Robbie Api timed out')); };
xhr.send(JSON.stringify({
source: CONTENT_SOURCE_SDK,
}));
});
}
/**
* @param {string} frame Base64 string of an image
* @param {string} id Session id to send images to
* @param {object} properties Labels to send to the api
*/
requestEmotions(id, frame) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST'
, `${RobbieApi.baseUrl}${REQUEST_EMOTIONS_ROUTE}?single=true&persist=false&gender=false`);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Robbie-Sdk-Web-X-Token', `${this._token}`);
xhr.onerror = () => { reject(xhr); };
xhr.ontimeout = () => { reject(new Error('Robbie Api timed out')); };
const timestamp = (new Date()).getTime();
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 201) {
const response = JSON.parse(xhr.responseText);
response.TIMESTAMP = timestamp;
resolve(response);
} else if (xhr.readyState === XMLHttpRequest.DONE) {
reject(xhr);
}
};
xhr.send(JSON.stringify({
user_id: 'ANONYMOUS',
timestamp: new Date(),
image: frame,
content: id,
source: CONTENT_SOURCE_SDK,
labels: this._properties
}));
});
}
}