-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
534 lines (461 loc) · 16.1 KB
/
Copy pathserver.js
File metadata and controls
534 lines (461 loc) · 16.1 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const os = require('os');
const net = require('net');
const SMB2 = require('@marsaud/smb2');
const app = express();
const PORT = process.env.PORT || 4880;
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Configuration management
const CONFIG_FILE = path.join(__dirname, 'config.json');
let config = {
asiairIp: '',
localPath: '',
interval: 30, // seconds
syncEnabled: false,
fileTypes: ['fits', 'fit', 'xisf']
};
function loadConfig() {
try {
if (fs.existsSync(CONFIG_FILE)) {
const data = fs.readFileSync(CONFIG_FILE, 'utf8');
config = { ...config, ...JSON.parse(data) };
}
} catch (err) {
log(`Failed to load config: ${err.message}`, 'error');
}
}
function saveConfig() {
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
} catch (err) {
log(`Failed to save config: ${err.message}`, 'error');
}
}
// Log management
const logs = [];
function log(message, type = 'info') {
const timestamp = new Date().toISOString();
const logEntry = { timestamp, message, type };
logs.push(logEntry);
if (logs.length > 2000) {
logs.shift();
}
console.log(`[${type.toUpperCase()}] ${message}`);
}
// Global sync state
let syncInProgress = false;
let syncTimer = null;
let lastSyncTime = null;
let discoveryActive = false;
// Scan local networks for port 445 (Samba)
async function discoverDevices() {
if (discoveryActive) return [];
discoveryActive = true;
log('Starting ASIAIR network discovery...', 'info');
const interfaces = os.networkInterfaces();
const targets = [];
// Add default ASIAIR IPs (10.0.0.1 for AP mode)
targets.push('10.0.0.1');
targets.push('asiair.local');
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
// e.g., 192.168.1.50 -> subnet 192.168.1
const ipParts = iface.address.split('.');
if (ipParts.length === 4) {
const subnet = ipParts.slice(0, 3).join('.');
// Scan standard local range (excluding router typically .1, but scan it anyway)
for (let i = 1; i <= 254; i++) {
const targetIp = `${subnet}.${i}`;
if (targetIp !== iface.address) {
targets.push(targetIp);
}
}
}
}
}
}
// Remove duplicates
const uniqueTargets = [...new Set(targets)];
const discovered = [];
// Check port 445 (SMB) helper
const checkPort = (ip, port = 445, timeout = 300) => {
return new Promise((resolve) => {
const socket = new net.Socket();
let status = false;
socket.setTimeout(timeout);
socket.on('connect', () => {
status = true;
socket.destroy();
});
socket.on('timeout', () => {
socket.destroy();
});
socket.on('error', () => {
socket.destroy();
});
socket.on('close', () => {
resolve(status);
});
socket.connect(port, ip);
});
};
// Run checks in chunks to avoid overloading OS sockets
const chunkSize = 30;
for (let i = 0; i < uniqueTargets.length; i += chunkSize) {
const chunk = uniqueTargets.slice(i, i + chunkSize);
const results = await Promise.all(
chunk.map(async (ip) => {
const isUp = await checkPort(ip, 445, 400);
if (isUp) {
// If port 445 is open, check if we can ping port 4400 or 4700 to confirm it's likely an ASIAIR
const isAsiairPort = await checkPort(ip, 4400, 200) || await checkPort(ip, 4700, 200);
return { ip, isAsiairPort };
}
return null;
})
);
for (const res of results) {
if (res) {
log(`Discovered SMB device at ${res.ip} (Confirmed ASIAIR Port: ${res.isAsiairPort})`, 'info');
discovered.push({
ip: res.ip,
name: res.ip === 'asiair.local' ? 'asiair.local' : (res.isAsiairPort ? 'ASIAIR Device' : 'Generic SMB share')
});
}
}
}
discoveryActive = false;
log(`Discovery complete. Found ${discovered.length} device(s).`, 'info');
return discovered;
}
// Recursive function to walk directories in SMB share
const MOUNT_ROOT = path.join(__dirname, 'mnt');
// Ensure mount directory exists
if (!fs.existsSync(MOUNT_ROOT)) {
fs.mkdirSync(MOUNT_ROOT, { recursive: true });
}
// Mount SMB share locally depending on operating system
function mountShare(ip, shareName, mountPath) {
const { execSync } = require('child_process');
const platform = os.platform();
if (platform === 'win32') {
// Windows: Use UNC path natively. No mount point needed.
const uncPath = `\\\\${ip}\\${shareName}`;
try {
fs.readdirSync(uncPath);
return uncPath;
} catch (err) {
return null;
}
}
// macOS and Linux require local mounting directories
if (!fs.existsSync(mountPath)) {
fs.mkdirSync(mountPath, { recursive: true });
}
// Attempt to unmount first to ensure clean state
try {
execSync(`umount -f "${mountPath}"`, { stdio: 'ignore' });
} catch (e) {}
if (platform === 'darwin') {
try {
const encodedShare = encodeURIComponent(shareName);
execSync(`mount_smbfs "//guest@${ip}/${encodedShare}" "${mountPath}"`, { stdio: 'ignore', timeout: 5000 });
log(`Mounted share "${shareName}" successfully to "${mountPath}"`, 'info');
return mountPath;
} catch (err) {
// If mount fails, check if the OS already has it mounted under /Volumes
const volumesPath = path.join('/Volumes', shareName);
if (fs.existsSync(volumesPath)) {
log(`Share "${shareName}" already mounted by macOS at "${volumesPath}". Utilizing existing mount.`, 'info');
return volumesPath;
}
log(`Share "${shareName}" is unavailable or inactive on device (skipping).`, 'info');
return null;
}
} else {
// Linux mounting
try {
execSync(`mount -t cifs -o guest,vers=2.0 "//${ip}/${shareName}" "${mountPath}"`, { stdio: 'ignore', timeout: 5000 });
log(`Mounted share "${shareName}" successfully to "${mountPath}"`, 'info');
return mountPath;
} catch (err) {
log(`Share "${shareName}" is unavailable or inactive on device (skipping).`, 'info');
return null;
}
}
}
// Recursively walk a local directory (asynchronous & optimized)
async function scanLocalDirectory(dirPath, fileTypes, baseDir, foundFiles = []) {
try {
if (!fs.existsSync(dirPath)) return foundFiles;
// Use withFileTypes: true to avoid calling stat on every directory entry
const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const entryName = entry.name;
if (entryName === '.' || entryName === '..' || entryName.startsWith('._') || entry.isSymbolicLink()) {
continue;
}
const fullPath = path.join(dirPath, entryName);
if (entry.isDirectory()) {
await scanLocalDirectory(fullPath, fileTypes, baseDir, foundFiles);
} else if (entry.isFile()) {
const ext = path.extname(entryName).toLowerCase().replace('.', '');
let matchesType = fileTypes.includes(ext);
if (!matchesType) {
if ((ext === 'fit' || ext === 'fits') && (fileTypes.includes('fit') || fileTypes.includes('fits'))) {
matchesType = true;
} else if ((ext === 'jpg' || ext === 'jpeg') && (fileTypes.includes('jpg') || fileTypes.includes('jpeg'))) {
matchesType = true;
}
}
if (matchesType) {
// Only fetch stat for matching files (saves network roundtrips)
let stat;
try {
stat = await fs.promises.stat(fullPath);
} catch (e) {
continue;
}
const relativePath = path.relative(baseDir, fullPath);
foundFiles.push({
absolutePath: fullPath,
remotePath: relativePath,
name: entryName,
size: stat.size,
mtime: stat.mtime
});
}
}
}
} catch (err) {
log(`Error walking directory "${dirPath}": ${err.message}`, 'error');
}
return foundFiles;
}
// Copy local file to destination folder (asynchronous & stream-based for SMB compatibility)
async function copyLocalFile(file, localBaseDir) {
const localFilePath = path.join(localBaseDir, file.remotePath);
const localFileDir = path.dirname(localFilePath);
if (!fs.existsSync(localFileDir)) {
await fs.promises.mkdir(localFileDir, { recursive: true });
}
try {
await fs.promises.access(localFilePath, fs.constants.F_OK);
const localStat = await fs.promises.stat(localFilePath);
if (localStat.size === file.size) {
return false; // already synced
}
} catch (e) {
// File doesn't exist, proceed to copy
}
log(`Copying: ${file.remotePath} (${(file.size / 1024 / 1024).toFixed(2)} MB)`, 'info');
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(file.absolutePath);
const writeStream = fs.createWriteStream(localFilePath);
const cleanup = () => {
readStream.destroy();
writeStream.end();
};
readStream.on('error', (err) => {
cleanup();
fs.unlink(localFilePath, () => {});
reject(err);
});
writeStream.on('error', (err) => {
cleanup();
fs.unlink(localFilePath, () => {});
reject(err);
});
writeStream.on('finish', () => {
resolve(true);
});
readStream.pipe(writeStream);
});
}
// Main sync cycle execution
async function runSync() {
if (syncInProgress) {
log('Sync already in progress, skipping schedule run.', 'warning');
return;
}
if (!config.asiairIp || !config.localPath) {
log('Sync configuration incomplete (IP or Local Path missing).', 'warning');
return;
}
// Validate local path exists
if (!fs.existsSync(config.localPath)) {
try {
fs.mkdirSync(config.localPath, { recursive: true });
} catch (err) {
log(`Local sync path does not exist and could not be created: ${err.message}`, 'error');
return;
}
}
syncInProgress = true;
log('Starting synchronization run...', 'info');
const sharesToScan = ['EMMC Images', 'Images', 'Udisk Images', 'Samba'];
let totalCopied = 0;
for (const shareName of sharesToScan) {
const localMountPath = path.join(MOUNT_ROOT, shareName.replace(/\s+/g, '_'));
// Attempt to mount the share
const activeSourcePath = mountShare(config.asiairIp, shareName, localMountPath);
if (!activeSourcePath) {
continue; // Skip unavailable shares
}
try {
log(`Scanning directory tree on "${shareName}"...`, 'info');
const filesToSync = await scanLocalDirectory(activeSourcePath, config.fileTypes, activeSourcePath);
log(`Found ${filesToSync.length} matching files on share "${shareName}".`, 'info');
let copiedCount = 0;
const relativeLocalSubdir = path.join(config.localPath, shareName);
for (const file of filesToSync) {
try {
const copied = await copyLocalFile(file, relativeLocalSubdir);
if (copied) {
copiedCount++;
totalCopied++;
}
} catch (copyErr) {
log(`Failed to copy "${file.remotePath}" from "${shareName}": ${copyErr.message}`, 'error');
}
}
log(`Completed scanning share "${shareName}". Copied ${copiedCount} new file(s).`, 'info');
} catch (scanErr) {
log(`Error scanning mounted share "${shareName}": ${scanErr.message}`, 'error');
}
}
lastSyncTime = new Date().toISOString();
log(`Sync run completed. Copied ${totalCopied} new file(s) in total.`, 'info');
syncInProgress = false;
}
// Manage scheduler
function startScheduler() {
stopScheduler();
if (config.syncEnabled) {
log(`Starting auto-sync timer (every ${config.interval} seconds)`, 'info');
syncTimer = setInterval(runSync, config.interval * 1000);
}
}
function stopScheduler() {
if (syncTimer) {
log('Stopping auto-sync timer.', 'info');
clearInterval(syncTimer);
syncTimer = null;
}
}
// API Routes
app.get('/api/config', (req, res) => {
res.json(config);
});
app.post('/api/config', (req, res) => {
const { asiairIp, localPath, interval, syncEnabled, fileTypes } = req.body;
if (interval !== undefined && (typeof interval !== 'number' || interval < 5)) {
return res.status(400).json({ error: 'Interval must be a number greater than or equal to 5 seconds.' });
}
config.asiairIp = asiairIp !== undefined ? asiairIp.trim() : config.asiairIp;
config.localPath = localPath !== undefined ? localPath.trim() : config.localPath;
config.interval = interval !== undefined ? interval : config.interval;
config.syncEnabled = syncEnabled !== undefined ? syncEnabled : config.syncEnabled;
config.fileTypes = fileTypes !== undefined ? fileTypes : config.fileTypes;
saveConfig();
// Restart scheduler with new parameters
startScheduler();
res.json({ message: 'Configuration saved successfully', config });
});
app.get('/api/status', (req, res) => {
// Check if local folder path exists and is writable
let localPathWritable = false;
if (config.localPath) {
try {
if (fs.existsSync(config.localPath)) {
fs.accessSync(config.localPath, fs.constants.W_OK);
localPathWritable = true;
}
} catch (e) {
localPathWritable = false;
}
}
res.json({
syncInProgress,
lastSyncTime,
schedulerActive: !!syncTimer,
localPathWritable,
localPathExists: config.localPath ? fs.existsSync(config.localPath) : false
});
});
app.post('/api/sync/now', async (req, res) => {
if (syncInProgress) {
return res.status(409).json({ error: 'Sync already in progress' });
}
// Run async without blocking response
runSync().catch((err) => log(`Sync failed: ${err.message}`, 'error'));
res.json({ message: 'Sync started' });
});
app.get('/api/discover', async (req, res) => {
try {
const devices = await discoverDevices();
res.json({ devices });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/logs', (req, res) => {
res.json({ logs });
});
app.post('/api/select-folder', (req, res) => {
const platform = os.platform();
const { exec } = require('child_process');
if (platform === 'darwin') {
exec(`osascript -e 'POSIX path of (choose folder with prompt "Select Local Sync Folder")'`, (error, stdout, stderr) => {
if (error) {
if (error.message.includes('-128')) {
// User canceled
return res.json({ canceled: true });
}
return res.status(500).json({ error: error.message });
}
const selectedPath = stdout.trim();
res.json({ path: selectedPath });
});
} else if (platform === 'win32') {
// Windows: Use PowerShell to open System.Windows.Forms.FolderBrowserDialog
const cmd = `powershell -NoProfile -Command "Add-Type -AssemblyName System.Windows.Forms; $f = New-Object System.Windows.Forms.FolderBrowserDialog; $f.Description = 'Select Local Sync Folder'; $f.ShowNewFolderButton = $true; if ($f.ShowDialog() -eq 'OK') { $f.SelectedPath }"`;
exec(cmd, (error, stdout, stderr) => {
if (error) {
return res.status(500).json({ error: error.message });
}
const selectedPath = stdout.trim();
if (!selectedPath) {
// User closed or canceled
return res.json({ canceled: true });
}
res.json({ path: selectedPath });
});
} else {
// Linux or others: check if Zenity GUI folder dialog tool is available
exec('which zenity', (err) => {
if (err) {
return res.status(501).json({ error: 'Folder browser is not available on your Linux desktop system. Please enter the directory path manually.' });
}
exec('zenity --file-selection --directory --title="Select Local Sync Folder"', (error, stdout) => {
if (error) {
// Cancelled
return res.json({ canceled: true });
}
res.json({ path: stdout.trim() });
});
});
}
});
// Load config and boot
loadConfig();
startScheduler();
app.listen(PORT, () => {
log(`ASIAIR Sync Web App listening on port ${PORT}`, 'info');
});