UNPKG

signals-api

Version:
448 lines (409 loc) 12.9 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _request = require('request'); var _request2 = _interopRequireDefault(_request); var _log2 = require('./log'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SignalsAPI = function () { function SignalsAPI(credential, region) { _classCallCheck(this, SignalsAPI); if (credential) { this._APIHeaders = { "X-Taste-User": credential.key, "X-Taste-Key": credential.token, "X-Taste-App": credential.domain }; } else { this._APIHeaders = {}; } var kEndPoints = { 'zh': 'https://signalsapi.tasteanalytics.cn:443', 'zh-2': 'https://signalsapi2.tasteanalytics.cn:443', 'alpha': 'https://alpha.tasteanalytics.com:443', 'beta': 'https://betaapi.tasteanalytics.com:443', 'en': 'https://signalsapi.stratifyd.com:443', 'omega': 'https://omega.tasteanalytics.com:2012' }; var endPoint = kEndPoints[region || 'en']; this.APIEndPoint(endPoint); } _createClass(SignalsAPI, [{ key: 'APIEndPoint', value: function APIEndPoint(endPoint) { if (arguments.length) { var value = 'https://signalsapi.tasteanalytics.com:443'; if (endPoint) { var match = endPoint.match(/(http(s?):\/\/)?([a-z0-9\-]*\.){1,}[a-z0-9\-]*(:[0-9]+)?/); if (match) { if (undefined === match[1]) { // the protocol is missing value = 'https://' + endPoint; } else { value = endPoint; } } } this._APIEndPoint = value; } return this._APIEndPoint; // return 'https://alpha.tasteanalytics.com:443' // return 'https://betaapi.tasteanalytics.com:443' // return 'https://192.168.0.2:2012' } }, { key: 'setCredential', value: function setCredential(json) { if (json.user) { this._APIHeaders["X-Taste-User"] = json.user; } if (json.key) { this._APIHeaders["X-Taste-User"] = json.key; } if (json.token) { this._APIHeaders["X-Taste-Key"] = json.token; } if (json.domain) { this._APIHeaders["X-Taste-App"] = json.domain; } } }, { key: 'login', value: function login(user, pwd, callback) { var url = this.APIEndPoint() + '/user'; var headers = _extends({}, this._APIHeaders); delete headers["X-Taste-User"]; delete headers["X-Taste-Key"]; var opts = { url: url, method: 'POST', headers: headers, json: true, gzip: true, strictSSL: false, body: { name: user, password: pwd } }; var self = this; var req = (0, _request2.default)(opts, function (error, response, body) { if (error) { error(error); } else { (0, _log2._log)('Status ' + response.statusCode); var credential = body.payload; self.setCredential(credential); } callback(error, body, response); }); return req; } }, { key: 'APICall', value: function APICall(path, method, body, handler, exOpts) { var insertPos = path.indexOf('?'); var tail = '_=' + new Date().getTime(); if (-1 === insertPos) { path += '?' + tail; } else { var pos = insertPos + 1; path = path.substring(0, pos) + tail + '&' + path.substring(pos); } var url = this.APIEndPoint() + path; (0, _log2._log)(method + ' ' + url); var headers = _extends({}, this._APIHeaders); var opts = _extends({ url: url, method: method, headers: headers, // json: true, gzip: true, strictSSL: false }, exOpts); if (body) { var Stream = require('stream'); if ((typeof body === 'undefined' ? 'undefined' : _typeof(body)) === 'object' && !(body instanceof Stream) && !(body instanceof Buffer)) { opts.body = JSON.stringify(body); opts.headers['content-type'] = 'application/json'; } else { opts.body = body; } } var req = (0, _request2.default)(opts, function (error, response, body) { if (error) { (0, _log2._error)(error); } // _log('Status '+response.statusCode); if (typeof body === 'string') { try { body = JSON.parse(body); } catch (e) { // this is not a json } } (0, _log2._log)(body); if (handler) { handler(error, body, response); } }); return req; } }, { key: 'APIGet', value: function APIGet(path, handler, exOpts) { return this.APICall(path, 'GET', null, handler, exOpts); } }, { key: 'APIPost', value: function APIPost(path, json, handler, exOpts) { return this.APICall(path, 'POST', json, handler, exOpts); } }, { key: 'APIPut', value: function APIPut(path, json, handler, exOpts) { return this.APICall(path, 'PUT', json, handler, exOpts); } }, { key: 'APIPatch', value: function APIPatch(path, json, handler, exOpts) { return this.APICall(path, 'PATCH', json, handler, exOpts); } }, { key: 'APIDelete', value: function APIDelete(path, json, handler, exOpts) { return this.APICall(path, 'DELETE', json, handler, exOpts); } }, { key: 'createJob', value: function createJob(config) { var TAJob = require('./RelationalObject/job'); return new TAJob(this, undefined, config); } }, { key: 'job', value: function job(fid, callback) { // download the job info var TAJob = require('./RelationalObject/job'); var job = new TAJob(this, fid, {}); if (fid) { job.requestConfiguration(callback); } return job; } }, { key: 'deleteJob', value: function deleteJob(fid, callback) { this.APIDelete('/user/jobs/' + fid, null, callback); } }, { key: 'getJobStatus', value: function getJobStatus(options, callback) { function calcSentiment(p, n) { p = +p, n = +n; if (isNaN(p) || isNaN(n)) { return 0; } if (p > 5 || n < -5) { var sum = p + n; return 5.0 * sum / (sum > 0 ? p : -n); } else { return p + n; } } var pageSize = options.pageSize || 25; var filter = options.filter; var url = '/user/jobs?limit=' + pageSize; if (!filter) filter = { current: 1 }; // url += '&filter='+encodeURIComponent(JSON.stringify(filter)); url += '&filter=' + JSON.stringify(filter); var sortBy = options.sortBy; var sortOrder = options.sortOrder; if (options.sortBy) { url += '&sort_by=["' + options.sortBy + '",' + options.sortOrder + ']'; } if (options.pageIndex && options.pageIndex > 0) { url += '&from=' + options.pageIndex * pageSize; } return this.APIGet(url, function (json, response, error) { var profiles = {}; if (json && json.payload) { profiles = json.payload; } if (profiles && profiles.items && profiles.items.length > 0) { if (!options.sortBy) { profiles.items.sort(function (a, b) { var dateA = a.time ? a.time : 0, dateB = b.time ? b.time : 0; return dateB - dateA; }); } profiles.items.forEach(function (p) { p.sentiment = p.overall_sentiment ? calcSentiment(p.overall_sentiment.positive, p.overall_sentiment.negative) : 0; }); } }); if (callback) { callback(error, profiles, response); } } // tempDir( callback ) { // if( this._tempFilePath ) { // callback(this._tempFilePath); // } else { // var temp = require('temp'); // temp.track(); // temp.mkdir('signals', (err, dirPath) => { // this._tempFilePath = dirPath; // callback(this._tempFilePath); // }) // } // } }, { key: 'queryRelationalObject', value: function queryRelationalObject(type, filter, callback) { var _this = this; if (!filter) { filter = { current: 1 }; } var url = '/user/' + type + '?filter=' + encodeURIComponent(JSON.stringify(filter)); return this.APICall(url, 'GET', null, function (error, body, response) { if (!error && body && body.payload) { var payload = body.payload; var total = payload.total, items = payload.items; var RelationalObject = require('./RelationalObject/object'); var result = { total: total, items: items.map(function (j) { var obj = new RelationalObject(_this, type, j); return obj; }) }; if (callback) { callback(error, result, response); } } }); } }, { key: 'createRelationalObject', value: function createRelationalObject(type, json, callback) { var _this2 = this; var url = '/user/' + type; return this.APICall(url, 'POST', json, function (error, body, response) { if (!error && body && body.payload) { var RelationalObject = require('./RelationalObject/object'); var obj = new RelationalObject(_this2, type, body.payload.meta); if (callback) { callback(error, obj, response); } } }); } }, { key: 'getRelationalObject', value: function getRelationalObject(type, fid, callback) { var _this3 = this; var url = '/user/' + type + '/' + fid; return this.APICall(url, 'GET', null, function (error, body, response) { if (!error && body && body.payload) { var RelationalObject = require('./RelationalObject/object'); var obj = new RelationalObject(_this3, type); obj.body = body.payload; if (callback) { callback(error, obj, response); } } }); } }, { key: 'shareWith', value: function shareWith(fid, type, groupId, accessLevel, callback) { var change = { objects: _defineProperty({}, type, [fid]), sharing: [{ _id: groupId, access: accessLevel }] }; return this.APICall("/groups", 'PATCH', change, callback); } }, { key: 'requireFields', value: function requireFields(json, fields) { for (var f in fields) { if (undefined !== json[f]) { throw new f() + " is missing"; } } } }, { key: 'createGroup', value: function createGroup(name, meta, callback) { requireFields(meta, ["companyName", "companyId"]); var body = { name: name, meta: _extends({}, meta) }; return this.APICall("/groups", "POST", body, callback); } }, { key: 'deleteGroup', value: function deleteGroup(groupId, callback) { return this.APICall("/groups/" + groupId, "DELETE", null, callback); } }, { key: 'updateGroup', value: function updateGroup(groupId, change, callback) { return this.APICall("/user/groups/" + groupId, "PATCH", change, callback); } }, { key: 'getGroup', value: function getGroup(groupId, callback) { return this.APICall("/groups/" + groupId, "GET", null, callback); } }, { key: 'changeUserAccess', value: function changeUserAccess(groupId, userId, accessLevel, callback) { var _this4 = this; this.getGroup(groupId, function (error, body, response) { if (!error) { var group = body.payload; var members = group.members; var found = false; var next = members ? members.map(function (m) { var _id = m._id; if (_id === userId) { found = true; m.access = accessLevel; } }) : []; if (!found) { next.push({ _id: userId, access: accessLevel }); } _this4.APICall("/groups/" + groupId, "PUT", { members: next }, callback); } else { callback(error, body, response); } }); } }, { key: 'dashboard', value: function dashboard(fid) { var Dashboard = require('./RelationalObject/dashboard'); return new Dashboard(this, fid); } }]); return SignalsAPI; }(); exports.default = SignalsAPI; module.exports = exports['default'];