-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
167 lines (142 loc) · 4.51 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const express = require("express");
const app = express();
const yaml = require("js-yaml");
const msgpack = require("msgpack");
const fs = require("fs");
const util = require("util");
const readdirPromise = util.promisify(fs.readdir);
const readFilePromise = util.promisify(fs.readFile);
require('dotenv').config();
const CONFIG = process.env;
async function getRoundsData() {
const dirPath = CONFIG.ROUNDS_PATH;
const roundsData = [];
const files = await readdirPromise(dirPath);
const filePromises = files.map((file) => {
const filePath = `${dirPath}/${file}`;
return readFilePromise(filePath).then((buffer) => {
const data = msgpack.unpack(buffer, { recursiveUnpack: true });
const roundId = data.id;
const mapName = dict.maps[data.map];
const startTime = unixTimeToDateTime(data.st, "full");
const endTime = unixTimeToDateTime(data.end, "full");
const roundData = `${mapName}, ${startTime} - ${endTime}`;
return { roundId, roundData };
});
});
const results = await Promise.all(filePromises)
roundsData.push(...results);
return roundsData;
}
let dict;
fs.readFile(`./${CONFIG.DICTIONARY_PATH}`, "utf8", (err, data) => {
if (err) {
console.error(err);
} else {
dict = yaml.load(data);
}
});
function unixTimeToDateTime(timestamp, type) {
const date = new Date(timestamp * 1000);
const day = date.getDate().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const year = date.getFullYear().toString().slice(-2);
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
if (type == 'full'){
return `${day}.${month}.${year} @ ${hours}:${minutes}:${seconds}`;
} else {
return `${day}.${month} @ ${hours}:${minutes}:${seconds}`;
}
}
async function decodeByDictionary(data) {
const decoded_logs = [];
const events = data.events;
const round_id = data.id;
const map = data.map;
for (const event of events) {
const eventType = event.e_type;
const eventData = event.data;
const eventTime = event.data.ts;
const template = dict.events[eventType];
if (!template) {
console.warn(`В словаре отсутствует пресет для ${eventType}`);
continue;
}
let title = template.title
? replacePlaceholders(template.title, data, eventData, round_id, map)
: "";
let desc = template.desc
? replacePlaceholders(template.desc, data, eventData, round_id, map)
: "";
let event_type = eventType;
let event_time = unixTimeToTime(eventTime, "time");
decoded_logs.push({ title, desc, event: event_type, time: event_time });
}
return decoded_logs;
}
function replacePlaceholders(str, data, eventData, round_id, map) {
return str.replace(/\{([^}]+)\}/g, (match, key) => {
const keys = key.split(".");
let value = data;
for (const k of keys) {
value = value[k];
if (value === undefined) {
value = eventData[k];
}
if (value === undefined) {
return "";
}
}
if (key === "id") {
return round_id;
}
if (key === "map") {
return dict.maps[map];
}
return value || "";
});
}
async function readLogsForRound(round_id) {
let filePath = `CONFIG.ROUNDS_PATH/${round_id}.msgpack`;
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, buffer) => {
if (err) {
reject(err);
} else {
const data = msgpack.unpack(buffer, { recursiveUnpack: true });
const decoded_data = decodeByDictionary(data);
resolve(decoded_data);
}
});
});
}
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
next();
});
app.get("/api/rounds/:roundId", async (req, res) => {
const round_id = req.params.roundId;
try {
const logs = await readLogsForRound(round_id);
res.json(logs);
} catch (err) {
console.error(err);
res.status(500).send({ message: "Error reading logs" });
}
});
app.get("/api/rounds", async (req, res) => {
try {
const roundsData = await getRoundsData();
res.json(roundsData);
} catch (err) {
console.error(err);
res.status(500).send({ message: "Error reading rounds data" });
}
});
app.listen(8000, () => {
console.log("Server listening on port 8000");
});