-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutils.ts
More file actions
344 lines (311 loc) · 10.9 KB
/
Copy pathutils.ts
File metadata and controls
344 lines (311 loc) · 10.9 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import apikeys from "@/config/apikeys.json" with { type: "json" };
import webappconfig from "@/config/webapp.json" with { type: "json" };
import { createCanvas, loadImage } from "@napi-rs/canvas";
import axios from "axios";
import { PathLike, promises as fs } from "fs";
import request, { gql } from "graphql-request";
import path from "path";
import pino from "pino";
import type { GraphQlQueryResponseData } from "@octokit/graphql";
// debug so access logs reach the dashboard buffer, its UI defaults to info+
const baseLogger = pino({ level: process.env.LOG_LEVEL || "debug" });
export const logger = (meta: ImportMeta | string) =>
baseLogger.child({ file: typeof meta === "string" ? meta : path.basename(meta.filename) });
export const sleep = (ms: number): Promise<unknown> =>
new Promise(resolve => setTimeout(resolve, ms));
export const clamp = (input: number, min: number, max: number): number =>
input <= min ? min : input >= max ? max : input;
const LUA_ESCAPES: Record<string, string> = {
"\\": "\\\\",
'"': '\\"',
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
};
// built from a string literal so no raw control bytes end up in this file
// eslint-disable-next-line no-control-regex -- escaping control bytes is the point
const LUA_UNSAFE = new RegExp('[\\\\"\\u0000-\\u001f\\u007f]', "g");
/**
* Quotes a string as a Lua short-string literal, safe to interpolate into generated source.
* Control bytes become 3 digit decimal escapes so a following digit cannot extend them.
* Bytes above 0x7f pass through, gmod's Lua strings are byte arrays not unicode.
*/
export const luaString = (value: string): string =>
`"${value.replace(
LUA_UNSAFE,
c => LUA_ESCAPES[c] ?? `\\${c.charCodeAt(0).toString().padStart(3, "0")}`
)}"`;
export const luaStringOrNil = (value?: string | null): string =>
value === undefined || value === null ? "nil" : luaString(value);
const DURATION_UNITS = {
y: 31556926,
mo: 2628000,
w: 604800,
d: 86400,
h: 3600,
m: 60,
s: 1,
};
/** Parses "1y2mo3w" style durations to seconds. Returns 0 when nothing matched. */
export const parseDuration = (input: string): number => {
let len = 0;
for (const match of input
.trim()
.toLowerCase()
.replace(/\s+/g, "")
.matchAll(/(\d+)(y|mo|w|d|h|m|s)/g)) {
const amount = parseInt(match[1]);
if (!isNaN(amount) && amount > 0) len += amount * DURATION_UNITS[match[2]];
}
return len;
};
export const f = (
name: string,
value: string,
inline?: boolean
): { name: string; value: string; inline: boolean }[] => [
{
name,
value,
inline: !!inline,
},
];
export const exists = async (path: PathLike): Promise<boolean> =>
fs
.access(path)
.then(() => true)
.catch(() => false);
export const getStackLines = (input: string, linestart: number, lineend?: number): string => {
const lines = input.split(/\r?\n/).map(str => " " + str);
const line = clamp(linestart, 0, lines.length) - 1;
const replace = lines
.slice(line, lineend ?? line + 1)
.map(line => ">>" + line.substring(2) + " <<");
lines.splice(line, lineend ? lineend - linestart : 1, ...replace);
return lines
.slice(clamp(line - 10 / 2, 0, lines.length), clamp(line + 10 / 2, 0, lines.length))
.join("\n");
};
export const AddonURIS = {
advdupe2: "https://github.com/wiremod/advdupe2/blob/master/",
aowl: "https://gitlab.com/metastruct/internal/aowl/-/blob/master/",
arcana: "https://github.com/Metastruct/Arcana/blob/master/",
cfw: "https://github.com/Metastruct/CFW/blob/main/",
easychat: "https://github.com/Earu/EasyChat/blob/master/",
epoe: "https://github.com/Metastruct/EPOE/blob/master/",
fast_addons: "https://gitlab.com/metastruct/internal/fast_addons/-/blob/master/",
gcompute: "https://github.com/Metastruct/gcompute/blob/master/",
luadev: "https://github.com/Metastruct/luadev/blob/master/",
metaconcord: "https://github.com/metastruct/gmod-metaconcord/blob/master/",
metastruct: "https://gitlab.com/metastruct/internal/metastruct/-/blob/master/",
metaworks: "https://gitlab.com/metastruct/metaworks/MetaWorks/-/blob/master/",
mining: "https://github.com/Metastruct/mining/blob/master",
mta: "https://gitlab.com/metastruct/mta_projects/mta/-/blob/master/",
mta_gamemode: "https://gitlab.com/metastruct/mta_projects/mta_gm/-/blob/master/",
"neo-chatsounds": "https://github.com/Earu/neo-chatsounds/blob/main/",
pac3: "https://github.com/CapsAdmin/pac3/blob/develop/",
sandbox_modded: "https://gitlab.com/metastruct/internal/qbox/-/blob/master/",
swcs: "https://gitlab.com/cynhole/swcs/-/blob/master/",
vrmod: "https://github.com/Metastruct/vrmod/blob/main/",
wire: "https://github.com/Metastruct/wire/blob/master/",
};
const LOOKUP_PATH = webappconfig.lookupPath;
export const GMOD_PATH_MATCH =
/^(?<path>(?:lua|gamemodes)\/(?<addon>[-_.A-Za-z0-9]+?|)?(?:\/.*)?\/(?<filename>[-_.A-Za-z0-9]+)\.(?<ext>[a-z]*))?(?::-?(?<linenos>\d+)-?(?<linenoe>\d+)?)?$/g;
export const getAsBase64 = async (url: string): Promise<string | null> => {
if (!url.match(/^https?:\/\/.+/)) return null;
try {
const res = await axios.get(url, { responseType: "arraybuffer" });
const contentType = res.headers["content-type"] || "image/png";
const base64 = Buffer.from(res.data, "binary").toString("base64");
return `data:${contentType};base64,${base64}`;
} catch {
return null;
}
};
interface GitlabResponse {
project: {
repository: {
blobs: {
nodes: [{ rawTextBlob: string }] | [];
};
};
};
}
export const matchGmodPath = (path: PathLike) => {
const [, fpath, addon, filename, ext, linenos, linenoe] =
new RegExp(GMOD_PATH_MATCH).exec(<string>path) || [];
return { fpath, addon, filename, ext, linenos, linenoe };
};
export const getOrFetchGmodFile = async (path: PathLike | undefined) => {
if (path === undefined) return;
const gpath = matchGmodPath(path);
const fullpath = LOOKUP_PATH + gpath.fpath;
if (await exists(fullpath)) {
const path = await fs.realpath(fullpath);
if (!path.startsWith(LOOKUP_PATH)) return undefined;
const file = await fs.readFile(fullpath, "utf8");
return gpath.linenos
? getStackLines(
file,
Number(gpath.linenos),
gpath.linenoe ? Number(gpath.linenoe) : undefined
)
: file;
} else {
const url: string | undefined = gpath.addon ? AddonURIS[gpath.addon] : undefined;
if (url) {
const provider = url.match(/([^./]+)\.com/);
if (!provider) return;
const isGithub = provider[1] === "github";
const gitlabEndpoint = "https://gitlab.com/api/graphql";
const repo = gpath.addon;
const owner = url.match(/\.com\/(.+?)\//)?.[1];
const branch = url.split("/").at(-2);
if (!owner) return;
let filecontent: string | undefined;
try {
if (isGithub) {
const github = await globalThis.MetaConcord.container.getService("Github");
const data = (await github.octokit.graphql(
`query text($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
object(expression: "${branch ?? "HEAD"}:${gpath.fpath}") {
... on Blob {
text
}
}
}
}`,
{ owner, repo }
)) as GraphQlQueryResponseData;
if (data.repository?.object?.text) {
filecontent = data.repository.object.text;
} else {
baseLogger.warn(
{ data, context: { path, url } },
"unexpected Github GraphQL response"
);
}
} else {
const query = gql`{
project(fullPath:"${url.match(/\.com\/(.+?)\/-/)?.[1]}") {
repository {
blobs(paths:"${gpath.fpath}"){
nodes{rawTextBlob}
}
}
}
}
`;
const data = await request<GitlabResponse>(
gitlabEndpoint,
query,
{},
{
authorization: `Bearer ${apikeys.gitlab}`,
}
);
if (data.project.repository.blobs.nodes[0]?.rawTextBlob) {
filecontent = data.project.repository.blobs.nodes[0].rawTextBlob;
} else {
baseLogger.info({ path, url }, "missing file from Gitlab repo");
}
}
} catch (err) {
baseLogger.error(
{ err, context: { path, gmod: gpath.fpath, owner, repo, url } },
"GraphQL request failed"
);
return;
}
if (filecontent)
filecontent = getStackLines(
filecontent,
Number(gpath.linenos),
gpath.linenoe ? Number(gpath.linenoe) : undefined
);
return filecontent;
}
}
};
export const makeSpeechBubble = async (
link: string,
flip?: boolean,
fillcolor?: string,
strokecolor?: string,
linewidth?: number
): Promise<Buffer> => {
const image = await loadImage(link);
const canvas = createCanvas(image.width, image.height);
const ctx = canvas.getContext("2d");
const w = canvas.width;
const h = canvas.height;
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(image, 0, 0);
if (flip) {
ctx.translate(w, 0);
ctx.scale(-1, 1);
}
ctx.globalCompositeOperation = fillcolor ? "source-over" : "destination-out";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.quadraticCurveTo(0, 0.1 * h, 0.6 * w, 0.1 * h);
ctx.quadraticCurveTo(0.6 * w, 0.15 * h, 0.5 * w, 0.2 * h);
ctx.quadraticCurveTo(0.75 * w, 0.2 * h, 0.75 * w, 0.1 * h);
ctx.quadraticCurveTo(w, 0.1 * h, w, 0);
if (fillcolor) ctx.fillStyle = fillcolor;
ctx.fill();
ctx.globalCompositeOperation = "source-over";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.quadraticCurveTo(0, 0.1 * h, 0.6 * w, 0.1 * h);
ctx.quadraticCurveTo(0.6 * w, 0.15 * h, 0.5 * w, 0.2 * h);
ctx.quadraticCurveTo(0.75 * w, 0.2 * h, 0.75 * w, 0.1 * h);
ctx.quadraticCurveTo(w, 0.1 * h, w, 0);
ctx.strokeStyle = strokecolor ?? "rgba(0, 0, 0, 0)";
ctx.lineWidth = linewidth ?? 4;
ctx.stroke();
return canvas.encode("png");
};
type SteamGroupCache = { members?: Set<string>; fetchedAt: number; refresh?: Promise<void> };
const steamGroups = new Map<string, SteamGroupCache>();
// a little under the hourly role sweep in services/Accounts, so every sweep sees fresh groups
const STEAM_GROUP_TTL = 50 * 60 * 1000;
// Steam answers 429 quickly, so a failed refresh is not retried before this
const STEAM_GROUP_RETRY = 5 * 60 * 1000;
const refreshSteamGroup = async (groupId: string, cache: SteamGroupCache): Promise<void> => {
cache.fetchedAt = Date.now();
const res = await axios.get<string>(
`https://steamcommunity.com/gid/${groupId}/memberslistxml?xml=1`,
{
headers: {
"User-Agent":
"Mozilla/5.0 (compatible; node-metaconcord/1.0; +https://metastruct.net)",
},
}
);
cache.members = new Set(
[...String(res.data).matchAll(/<steamID64>(\d+)<\/steamID64>/g)].map(m => m[1])
);
};
/** Membership of a public Steam group, by group id64, cached for an hour. */
export const isSteamGroupMember = async (groupId: string, steamId64: string): Promise<boolean> => {
let cache = steamGroups.get(groupId);
if (!cache) {
cache = { fetchedAt: 0 };
steamGroups.set(groupId, cache);
}
const age = Date.now() - cache.fetchedAt;
const stale = cache.members ? age > STEAM_GROUP_TTL : age > STEAM_GROUP_RETRY;
if (stale) {
const c = cache;
c.refresh ??= refreshSteamGroup(groupId, c).finally(() => {
c.refresh = undefined;
});
await c.refresh.catch(err => {
baseLogger.error(err, `failed refreshing steam group ${groupId}`);
});
}
return !!cache.members?.has(steamId64);
};