lanshare/server.js
274 lines · javascript
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
const express = require('express');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');

const app = express();
const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf-8'));

app.use(express.json());
app.use(express.static('public'));

function getAllIPs() {
  const interfaces = require('os').networkInterfaces();
  const ips = [];
  
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        ips.push({
          name: name,
          address: iface.address,
          mac: iface.mac,
          family: iface.family
        });
      }
    }
  }
  
  return ips;
}

function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

function formatDateTime(date) {
  const d = new Date(date);
  return d.toLocaleString('zh-CN');
}

function getFileList(folderPath, relativePath = '') {
  const fullPath = path.resolve(folderPath, relativePath);
  
  if (!fs.existsSync(fullPath)) {
    return { error: '文件夹不存在', files: [], folders: [] };
  }
  
  const items = fs.readdirSync(fullPath, { withFileTypes: true });
  const files = [];
  const folders = [];
  
  for (const item of items) {
    if (item.name.startsWith('.')) continue;
    
    const stats = fs.statSync(path.join(fullPath, item.name));
    const itemPath = path.join(relativePath, item.name);
    
    if (item.isDirectory()) {
      folders.push({
        name: item.name,
        path: itemPath,
        modified: formatDateTime(stats.mtime)
      });
    } else {
      files.push({
        name: item.name,
        path: itemPath,
        size: formatFileSize(stats.size),
        sizeBytes: stats.size,
        modified: formatDateTime(stats.mtime),
        type: mime.lookup(item.name) || 'application/octet-stream'
      });
    }
  }
  
  return {
    currentPath: relativePath,
    folders: folders.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN')),
    files: files.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
  };
}

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/api/folders', (req, res) => {
  res.json(config.sharedFolders);
});

app.get('/api/files', (req, res) => {
  const folderIndex = parseInt(req.query.folderIndex) || 0;
  const folder = config.sharedFolders[folderIndex];
  const relativePath = req.query.path || '';
  
  if (!folder) {
    return res.status(404).json({ error: '文件夹不存在' });
  }
  
  const fileList = getFileList(folder.path, relativePath);
  res.json({
    folderName: folder.name,
    folderDescription: folder.description,
    folderIndex,
    ...fileList
  });
});

/**
 * 解析文件路径并验证权限
 * @param {number} folderIndex - 文件夹索引
 * @param {string} filePath - 文件相对路径
 * @returns {Object} 包含 fullPath、folder、stats 或错误信息
 */
function resolveFile(folderIndex, filePath) {
  const folder = config.sharedFolders[folderIndex];
  if (!folder) {
    return { error: '文件夹不存在', status: 404 };
  }

  const fullPath = path.resolve(folder.path, filePath);

  if (!fullPath.startsWith(path.resolve(folder.path))) {
    return { error: '禁止访问', status: 403 };
  }

  if (!fs.existsSync(fullPath)) {
    return { error: '文件不存在', status: 404 };
  }

  const stats = fs.statSync(fullPath);
  if (stats.isDirectory()) {
    return { error: '不能操作文件夹', status: 400 };
  }

  if (config.maxFileSize && stats.size > config.maxFileSize) {
    return { error: '文件过大', status: 400 };
  }

  return { fullPath, folder, stats };
}

/**
 * 短链接下载文件
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * 路由格式: /d/:folderIndex/* (例如: /d/0/folder/file.txt)
 */
app.get('/d/:folderIndex/*', (req, res) => {
  if (!config.allowDownload) {
    return res.status(403).json({ error: '下载已禁用' });
  }

  const folderIndex = parseInt(req.params.folderIndex);
  const filePath = decodeURIComponent(req.params[0]);

  if (!filePath) {
    return res.status(400).json({ error: '文件路径不能为空' });
  }

  const result = resolveFile(folderIndex, filePath);
  if (result.error) {
    return res.status(result.status).json({ error: result.error });
  }

  res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(path.basename(result.fullPath))}"`);
  res.setHeader('Content-Length', result.stats.size);
  res.setHeader('Content-Type', mime.lookup(result.fullPath) || 'application/octet-stream');

  fs.createReadStream(result.fullPath).pipe(res);
});

/**
 * 短链接预览文件
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * 路由格式: /p/:folderIndex/* (例如: /p/0/folder/image.jpg)
 */
app.get('/p/:folderIndex/*', (req, res) => {
  const folderIndex = parseInt(req.params.folderIndex);
  const filePath = decodeURIComponent(req.params[0]);

  if (!filePath) {
    return res.status(400).json({ error: '文件路径不能为空' });
  }

  const result = resolveFile(folderIndex, filePath);
  if (result.error) {
    return res.status(result.status).json({ error: result.error });
  }

  res.setHeader('Content-Type', mime.lookup(result.fullPath) || 'application/octet-stream');

  fs.createReadStream(result.fullPath).pipe(res);
});

app.get('/api/download', (req, res) => {
  if (!config.allowDownload) {
    return res.status(403).json({ error: '下载已禁用' });
  }

  const folderIndex = parseInt(req.query.folderIndex) || 0;
  const filePath = req.query.path;

  if (!filePath) {
    return res.status(400).json({ error: '文件路径不能为空' });
  }

  const result = resolveFile(folderIndex, filePath);
  if (result.error) {
    return res.status(result.status).json({ error: result.error });
  }

  res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(path.basename(result.fullPath))}"`);
  res.setHeader('Content-Length', result.stats.size);
  res.setHeader('Content-Type', mime.lookup(result.fullPath) || 'application/octet-stream');

  fs.createReadStream(result.fullPath).pipe(res);
});

app.get('/api/preview', (req, res) => {
  const folderIndex = parseInt(req.query.folderIndex) || 0;
  const filePath = req.query.path;

  if (!filePath) {
    return res.status(400).json({ error: '文件路径不能为空' });
  }

  const result = resolveFile(folderIndex, filePath);
  if (result.error) {
    return res.status(result.status).json({ error: result.error });
  }

  res.setHeader('Content-Type', mime.lookup(result.fullPath) || 'application/octet-stream');

  fs.createReadStream(result.fullPath).pipe(res);
});

const PORT = config.port || 8080;
const HOST = config.host || '0.0.0.0';

app.listen(PORT, HOST, () => {
  const allIPs = getAllIPs();
  const folderCount = config.sharedFolders.length;
  
  let ipLines = '';
  allIPs.forEach((ip, index) => {
    const isLast = index === allIPs.length - 1;
    const prefix = isLast ? '└─' : '├─';
    const lineText = `http://${ip.address}:${PORT} (${ip.name})`;
    const paddingLength = Math.max(0, 44 - lineText.length);
    const padding = ' '.repeat(paddingLength);
    ipLines += `║  ${prefix} ${lineText}${padding}║\n`;
  });
  
  if (allIPs.length === 0) {
    ipLines = '║  └─ 未检测到可用网卡                          ║\n';
  }
  
  console.log(`
╔════════════════════════════════════════════════════════╗
║          局域网文件分享服务器已启动                      ║
╠════════════════════════════════════════════════════════╣
║  本地访问:http://localhost:${PORT}                      ║
║  局域网访问:                                            ║
${ipLines}║  分享文件夹数量:${String(folderCount).padEnd(48, ' ')}║
╚════════════════════════════════════════════════════════╝
  `);
});