1 | const fs = require('fs');
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | function sanitizeTags(value, telegraf) {
|
7 | const blacklist = telegraf ? /:|\||,/g : /:|\||@|,/g;
|
8 |
|
9 | return String(value).replace(blacklist, '_');
|
10 | }
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | function formatTags(tags, telegraf) {
|
16 | if (Array.isArray(tags)) {
|
17 | return tags;
|
18 |
|
19 | } else {
|
20 | return Object.keys(tags).map(key => {
|
21 | return `${sanitizeTags(key, telegraf)}:${sanitizeTags(tags[key], telegraf)}`;
|
22 | });
|
23 | }
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function overrideTags (parent, child, telegraf) {
|
31 | const childCopy = {};
|
32 | const toAppend = [];
|
33 | formatTags(child, telegraf).forEach(tag => {
|
34 | const idx = typeof tag === 'string' ? tag.indexOf(':') : -1;
|
35 | if (idx < 1) {
|
36 | toAppend.push(tag);
|
37 | } else {
|
38 | childCopy[tag.substring(0, idx)] = tag.substring(idx + 1);
|
39 | }
|
40 | });
|
41 | const result = parent.map(tag => {
|
42 | const idx = typeof tag === 'string' ? tag.indexOf(':') : -1;
|
43 | if (idx < 1) {
|
44 | return tag;
|
45 | }
|
46 | const key = tag.substring(0, idx);
|
47 | if (childCopy.hasOwnProperty(key)) {
|
48 | const value = childCopy[key];
|
49 | delete childCopy[key];
|
50 | return `${key}:${value}`;
|
51 | }
|
52 | return tag;
|
53 | });
|
54 | Object.keys(childCopy).forEach(key => {
|
55 | result.push(`${key}:${childCopy[key]}`);
|
56 | });
|
57 | return result.concat(toAppend);
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | function formatDate(date) {
|
64 | let timestamp;
|
65 | if (date instanceof Date) {
|
66 |
|
67 | timestamp = Math.round(date.getTime() / 1000);
|
68 | } else if (date instanceof Number) {
|
69 |
|
70 | timestamp = Math.round(date);
|
71 | }
|
72 | return timestamp;
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | function intToIP(int) {
|
79 | const part1 = int & 255;
|
80 | const part2 = ((int >> 8) & 255);
|
81 | const part3 = ((int >> 16) & 255);
|
82 | const part4 = ((int >> 24) & 255);
|
83 |
|
84 | return `${part4}.${part3}.${part2}.${part1}`;
|
85 | }
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | function getDefaultRoute() {
|
91 | try {
|
92 | const fileContents = fs.readFileSync('/proc/net/route', 'utf8');
|
93 | const routes = fileContents.split('\n');
|
94 | for (const routeIdx in routes) {
|
95 | const fields = routes[routeIdx].trim().split('\t');
|
96 | if (fields[1] === '00000000') {
|
97 | const address = fields[2];
|
98 |
|
99 | const littleEndianAddress = address.match(/.{2}/g).reverse().join('');
|
100 | return intToIP(parseInt(littleEndianAddress, 16));
|
101 | }
|
102 | }
|
103 | } catch (e) {
|
104 | console.error('Could not get default route from /proc/net/route');
|
105 | }
|
106 | return null;
|
107 | }
|
108 |
|
109 | module.exports = {
|
110 | formatTags: formatTags,
|
111 | overrideTags: overrideTags,
|
112 | formatDate: formatDate,
|
113 | getDefaultRoute: getDefaultRoute,
|
114 | sanitizeTags: sanitizeTags
|
115 | };
|