File size: 3,514 Bytes
c3f1ebb
 
 
 
389beed
c3f1ebb
 
 
 
 
 
b24d2f6
ad08f49
b24d2f6
 
 
 
 
 
 
 
 
 
 
 
ad08f49
2551fa7
 
 
 
 
 
 
 
389beed
 
 
 
 
 
 
 
 
2551fa7
 
 
 
 
 
 
 
 
 
 
 
 
389beed
f6220d1
389beed
 
 
 
 
 
2551fa7
 
 
 
 
 
1ea5cda
 
389beed
 
 
 
 
 
 
 
 
 
 
 
2551fa7
 
 
 
389beed
 
2551fa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389beed
1ea5cda
389beed
0b38401
2551fa7
389beed
 
 
 
 
 
1ea5cda
389beed
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
const express = require('express');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json({ limit: '10mb' }));

const AUTH_TOKEN = process.env.API_TOKEN;

// 🔐 鉴权中间件
app.use((req, res, next) => {
    const auth = req.headers.authorization;
    if (!auth || !auth.startsWith('Bearer ')) {
        return res.status(401).send('Unauthorized');
    }
    const token = auth.slice(7);
    if (token !== AUTH_TOKEN) {
        return res.status(401).send('Unauthorized');
    }
    next();
});

const safeUnlink = (file) => {
    try {
        if (fs.existsSync(file)) fs.unlinkSync(file);
    } catch (e) {
        console.error('Cleanup failed:', file, e.message);
    }
};

/**
 * 核心引擎:将所有图形转为路径并执行布尔运算
 */
const runInkscape = (svg, mode) => {
    return new Promise((resolve, reject) => {
        const id = crypto.randomUUID();
        const inputFile = path.join('/tmp', `${id}_in.svg`);
        const outputFile = path.join('/tmp', `${id}_out.svg`);

        const cleanup = () => {
            safeUnlink(inputFile);
            safeUnlink(outputFile);
        };

        try {
            // 预处理
            const processedSvg = svg.replace(/currentColor/g, '#000000');
            fs.writeFileSync(inputFile, processedSvg);
        } catch (err) {
            cleanup();
            return reject(err);
        }

        let coreActions = ['object-to-path'];

        if (mode === 'stroke') {
            coreActions.push('object-stroke-to-path', 'path-union');
        } else if (mode === 'fill') {
            coreActions.push('object-set-property:fill,#000000', 'path-union');
        } else if (mode === 'stroke-fill') {
            coreActions.push(
                'object-set-property:fill,#000000',
                'object-stroke-to-path',
                'select-all',
                'path-union'
            );
        }

        const actions = [
            `file-open:${inputFile}`,
            'select-all',
            ...coreActions,
            `export-filename:${outputFile}`,
            'export-plain-svg',
            'export-do',
            'file-close'
        ].join(';');

        const command = `xvfb-run -a inkscape --actions="${actions}"`;

        exec(command, (error, stdout, stderr) => {
            if (error) {
                cleanup();
                return reject(new Error(stderr || error.message));
            }

            if (!fs.existsSync(outputFile)) {
                cleanup();
                return reject(new Error('Output SVG not generated'));
            }

            try {
                const result = fs.readFileSync(outputFile, 'utf8');

                const dValues = [];
                const pathMatch = /<path[^>]+d="([^"]+)"/g;
                let match;
                while ((match = pathMatch.exec(result)) !== null) {
                    dValues.push(match[1]);
                }

                cleanup();
                resolve(dValues.join(' '));
            } catch (err) {
                cleanup();
                reject(err);
            }
        });
    });
};


app.post('/convert/:mode', async (req, res) => {
    try {
        const d = await runInkscape(req.body.svg, req.params.mode);
        res.send(d);
    } catch (err) { res.status(500).send(err.message); }
});

app.listen(7860);