-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
executable file
·95 lines (79 loc) · 2.34 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
#!/usr/bin/env node
const path = require('node:path');
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
const log = require('./lib/log');
const cfg = require('./lib/config');
if (process.argv.length !== 3) {
console.log('mimejs\n\nusage: xdg-open { file | URL }');
process.exit(1);
}
const main = async () => {
const fatal = async (msg) => {
await log.write('error', msg);
console.error(msg);
return process.exit(1);
};
const esc = (value) => {
return value.replace(/'/g, "'\\''");
};
const arg = esc(process.argv[2]);
const vars = {
'$arg': `'${arg}'`
};
const sub = (cmd) => {
for (const key in vars) {
cmd = cmd.replace(key, () => vars[key]);
}
return cmd;
};
const execute = async (source, cmd) => {
const command = sub(cmd);
await log.write(source, command);
return await exec(`( ${command} & ) > /dev/null 2>&1`);
};
const config = await cfg.read();
if (!config) {
return await fatal('Config file not found or not readable');
}
// protocols
if (arg.match(/^[a-z]+:\/l?\/.+$/gi)) { // l? is for msteams support
const protocols = config['protocols'] || {};
for (const key in protocols) {
if (key.match(/^[a-z]+:\/l?\/.*$/gi)) {
if (arg.startsWith(key)) {
return await execute(`protocol:${key}`, protocols[key]);
}
}
}
}
// extensions
const ext = path.extname(arg).replace('.', '').toLowerCase();
if (ext) {
const extensions = config['extensions'] || {};
for (const key in extensions) {
const splits = key.split(',');
for (let i = 0; i < splits.length; i++) {
if (ext === splits[i].trim().toLowerCase()) {
return await execute(`extension:${ext}`, extensions[key]);
}
}
}
}
const match = (value, key) => {
const expression = `^${key.replace(/\*+/gi, '.+')}$`;
return value.match(new RegExp(expression, 'gi'));
};
// mimetypes
try {
const mimetypes = config['mimetypes'] || {};
const { stdout } = await exec(`file -L -E --brief --mime-type '${arg}'`);
for (const key in mimetypes) {
if (match(stdout.trim(), key)) {
return await execute(`mimetype:${key}`, mimetypes[key]);
}
}
} catch (e) {}
return await fatal(`No suitable command: ${arg}`);
}
main();