1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-21 09:38:01 +02:00
joplin/packages/lib/net-utils.js

41 lines
1002 B
JavaScript
Raw Normal View History

2020-11-05 18:58:23 +02:00
const shim = require('./shim').default;
2017-07-10 20:09:58 +02:00
const netUtils = {};
netUtils.ip = async () => {
const response = await shim.fetch('https://api.ipify.org/?format=json');
2017-07-10 20:09:58 +02:00
if (!response.ok) {
2019-09-19 23:51:18 +02:00
throw new Error(`Could not retrieve IP: ${await response.text()}`);
2017-07-10 20:09:58 +02:00
}
const ip = await response.json();
2017-07-10 20:09:58 +02:00
return ip.ip;
2019-07-29 15:43:53 +02:00
};
2017-07-10 20:09:58 +02:00
netUtils.findAvailablePort = async (possiblePorts, extraRandomPortsToTry = 20) => {
const tcpPortUsed = require('tcp-port-used');
for (let i = 0; i < extraRandomPortsToTry; i++) {
possiblePorts.push(Math.floor(8000 + Math.random() * 2000));
}
let port = null;
for (let i = 0; i < possiblePorts.length; i++) {
const inUse = await tcpPortUsed.check(possiblePorts[i]);
if (!inUse) {
port = possiblePorts[i];
break;
}
}
return port;
2019-07-29 15:43:53 +02:00
};
netUtils.mimeTypeFromHeaders = headers => {
if (!headers || !headers['content-type']) return null;
const splitted = headers['content-type'].split(';');
return splitted[0].trim().toLowerCase();
2019-07-29 15:43:53 +02:00
};
2019-07-29 15:43:53 +02:00
module.exports = { netUtils };