robbie-sdk
Version:
Robbie Visio SDK to send events for analaysis
118 lines (108 loc) • 3.15 kB
JavaScript
import Session from './Session';
import RobbieApi from './RobbieApi';
export default class RobbieVisioSdk {
constructor() {
this.robbieApi = null;
this.session = null;
this._video = null;
this._canvas = null;
}
/**
* @param token Api token to authenticate client
* @param onEmotionsReceived {function} Callback executed when emotions are received
* @param properties {object} Group of labels to send with the frame
*/
init(token, properties, onEmotionsReceived) {
this.robbieApi = new RobbieApi(token, properties);
return this.validateCameraPermissions()
.then(() => this.createSession())
.then(session => session.startRecording(onEmotionsReceived));
}
silentInit(token) {
this.robbieApi = new RobbieApi(token);
}
/**
* Finds UserMedia object through different types of browsers and returns it
* @returns {*}
* @private
*/
static _findNavigator() {
return navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
}
/**
* Create canvas and video tag inside the document
* @private
*/
_createImageCaptureElements() {
this._video = document.createElement('video');
this._canvas = document.createElement('canvas');
this._canvas.width = 600;
this._canvas.height = 400;
}
/**
* Destroy video and canvas tag in document;
* @private
*/
_destroyImageCaptureElements() {
if (this._video != null) {
this._video.remove();
}
if (this._canvas != null) {
this._canvas.remove();
}
this._video = null;
this._canvas = null;
}
validateCameraPermissions() {
return new Promise((resolve, reject) => {
if (navigator === null) {
reject(new Error('No navigator Found'));
}
navigator.getUserMedia = RobbieVisioSdk._findNavigator();
navigator.getUserMedia({
video: {
width: {},
height: { min: 720, max: 1024 },
facingMode: 'user',
frameRate: 30
}
},
stream => resolve(stream),
() => reject(new Error('User declined permission')));
});
}
/**
* @returns {Promise.<Session>} Contains a Sessions object with proper methods to start/stop
* event sending.
*/
createSession() {
if (this.session != null) {
return new Promise((resolve, reject) => reject(new Error('First close opened session')));
}
if (this.robbieApi == null) {
return new Promise((resolve, reject) => reject(new Error('First init RobbieVisio!')));
}
return this.validateCameraPermissions()
.then(() => this.robbieApi.requestNewSession())
.then((response) => {
this._createImageCaptureElements();
this.session = new Session(response.id, this);
return this.session;
});
}
/**
* If Session is being recorded, close it
*/
close() {
if (this.session == null) {
console.warn('To close the session, start it first!');
return;
}
this.session.close();
this._destroyImageCaptureElements();
this.session = null;
}
}