This example runs a local version of the 51Degrees cloud API using both the device detection and IP intelligence on-premise engines.
This example runs a local version of the 51Degrees cloud API using both the device detection and IP intelligence on-premise engines. See the cloud API documentation for details of the endpoints provided.
The cloud examples can be run against this local API by setting the '_51DEGREES_CLOUD_ENDPOINT' environment variable to 'http://localhost:5225/'. Any value can be used for the resource key when using the local API.
The paths to the data files should be provided as 2 consecutive command line parameters.
const path = require('path');
const require51 = (requestedPackage) => {
try {
return require(path.join(__dirname, '/../../../../node_modules/', requestedPackage));
} catch (e) {
try {
return require(requestedPackage);
} catch (e2) {
return require(requestedPackage);
}
}
};
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const zlib = require('zlib');
const core = require51('fiftyone.pipeline.core');
const DeviceDetectionOnPremise =
require51('fiftyone.devicedetection.onpremise').DeviceDetectionOnPremise;
require51('fiftyone.ipintelligence.onpremise').IpIntelligenceOnPremise;
const ExampleUtils = require(path.join(__dirname,
'/../../exampleUtils')).ExampleUtils;
const HASH_FILE_NAMES = [
'TAC-HashV41.hash',
'51Degrees-EnterpriseV4.1.hash',
'51Degrees-LiteV4.1.hash'
];
const IPI_FILE_NAMES = [
'51Degrees-EnterpriseIpiV41.ipi',
'51Degrees-LiteV41.ipi'
];
const PORT = 5225;
let pipeline;
let ipDataFilePath;
const setPipeline = (deviceDataFile, ipDataFile) => {
ipDataFilePath = ipDataFile;
const deviceEngine = new DeviceDetectionOnPremise({
dataFilePath: deviceDataFile,
performanceProfile: 'MaxPerformance',
licenceKeys: '',
autoUpdate: false,
updateOnStart: false,
fileSystemWatcher: false
});
dataFilePath: ipDataFile,
performanceProfile: 'LowMemory',
licenceKeys: '',
autoUpdate: false,
updateOnStart: false,
fileSystemWatcher: false
});
pipeline = new core.PipelineBuilder()
.add(deviceEngine)
.add(ipEngine)
.build();
pipeline.on('error', console.error);
};
const getEngines = function () {
return Object.values(pipeline.flowElements).filter(function (element) {
return element.dataKey === 'device' || element.dataKey === 'ip';
});
};
const accessibleProperties = function (res) {
const products = {};
for (const engine of getEngines()) {
const properties = [];
Object.values(engine.properties).forEach(function (property) {
properties.push({
Name: property.name,
Type: property.type,
Category: property.category,
DelayExecution: false
});
});
products[engine.dataKey] = { Properties: properties };
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ Products: products }));
};
const evidenceKeys = function (res) {
const keys = new Set();
for (const engine of getEngines()) {
for (const key of engine.evidenceKeyFilter.list) {
keys.add(key);
}
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(Array.from(keys)));
};
const processEvidence = function (req, res, query, body) {
const flowData = pipeline.createFlowData();
flowData.evidence.addFromRequest(req);
for (const [key, value] of Object.entries(query)) {
flowData.evidence.add('query.' + key, value);
}
for (const [key, value] of Object.entries(body)) {
flowData.evidence.add('query.' + key, value);
}
flowData.process().then(function () {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(flowData.jsonbundler.json));
});
};
const downloadIpiGz = function (res) {
const compressed = zlib.gzipSync(fs.readFileSync(ipDataFilePath));
const md5 = crypto.createHash('md5').update(compressed).digest('hex');
res.setHeader('Content-Type', 'application/gzip');
res.setHeader(
'Content-Disposition',
`attachment; filename="${path.basename(ipDataFilePath)}.gz"`);
res.setHeader('Content-MD5', md5);
res.end(compressed);
};
const server = http.createServer((req, res) => {
const parsed = new URL(req.url, `http:
const pathName = parsed.pathname.toLowerCase();
const query = {};
for (const [key, value] of parsed.searchParams) {
query[key] = value;
}
let bodyText = '';
req.on('data', function (chunk) {
bodyText += chunk;
});
req.on('end', function () {
const body = {};
if (bodyText.length > 0 &&
(req.headers['content-type'] || '')
.indexOf('application/x-www-form-urlencoded') !== -1) {
for (const [key, value] of new URLSearchParams(bodyText)) {
body[key] = value;
}
}
if (pathName === '/accessibleproperties' ||
pathName.startsWith('/accessibleproperties/')) {
accessibleProperties(res);
} else if (pathName === '/evidencekeys' ||
pathName.startsWith('/evidencekeys/')) {
evidenceKeys(res);
} else if (pathName === '/json' || pathName.endsWith('.json')) {
processEvidence(req, res, query, body);
} else if (pathName === '/download-ipi-gz') {
downloadIpiGz(res);
} else {
res.statusCode = 404;
res.end('Not found');
}
});
});
if (process.env.JEST_WORKER_ID === undefined) {
const args = process.argv.slice(2);
let deviceDataFile = args.length > 0 ? args[0] : undefined;
if (deviceDataFile === undefined) {
for (const fileName of HASH_FILE_NAMES) {
if (deviceDataFile !== undefined) break;
}
}
let ipDataFile = args.length > 1 ? args[1] : undefined;
if (ipDataFile === undefined) {
for (const fileName of IPI_FILE_NAMES) {
if (ipDataFile !== undefined) break;
}
}
if (deviceDataFile !== undefined && ipDataFile !== undefined) {
console.log(`Device detection data file: ${deviceDataFile}`);
console.log(`IP intelligence data file: ${ipDataFile}`);
setPipeline(deviceDataFile, ipDataFile);
server.listen(PORT, '0.0.0.0');
console.log(`Local cloud API listening on: http:
} else {
if (deviceDataFile === undefined) {
console.error('Failed to find a device detection data file. ' +
'Make sure the cxx/data submodule has been fetched by running ' +
'`git submodule update --init --recursive`. The full path to a ' +
'data file can be specified as the first command line argument');
}
if (ipDataFile === undefined) {
console.error('Failed to find an IP intelligence data file. ' +
'Make sure the cxx/data submodule has been fetched by running ' +
'`git submodule update --init --recursive`. The full path ' +
'to a data file can be specified as the second command line ' +
'argument');
}
}
};
module.exports = {
server,
setPipeline
};
Definition fiftyone.ipintelligence.onpremise/examples/onpremise/exampleUtils.js:203
On premise version of the 51Degrees IP Intelligence Engine Uses a data file to process evidence in Fl...
Definition ipIntelligenceOnPremise.js:101