-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
181 lines (152 loc) · 4.82 KB
/
Copy pathserver.js
File metadata and controls
181 lines (152 loc) · 4.82 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
const express = require('express');
const pg = require('pg');
const multer = require('multer');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// Create uploads directory if it doesn't exist
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir);
}
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${Math.random().toString(36).substr(2, 9)}.wav`);
}
});
const upload = multer({ storage });
// PostgreSQL client
const pool = new pg.Pool({
user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || 'postgres',
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
database: process.env.DB_NAME || 'voice_recordings'
});
// Initialize database
async function initializeDatabase() {
try {
const client = await pool.connect();
// Create table if it doesn't exist
await client.query(`
CREATE TABLE IF NOT EXISTS recordings (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
file_size INTEGER NOT NULL,
duration FLOAT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
description TEXT
);
`);
console.log('Database initialized successfully');
client.release();
} catch (error) {
console.error('Error initializing database:', error);
}
}
// Routes
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
// Get all recordings
app.get('/api/recordings', async (req, res) => {
try {
const result = await pool.query(
'SELECT id, filename, file_size, duration, created_at, description FROM recordings ORDER BY created_at DESC'
);
res.json(result.rows);
} catch (error) {
console.error('Error fetching recordings:', error);
res.status(500).json({ error: 'Failed to fetch recordings' });
}
});
// Upload audio recording
app.post('/api/recordings', upload.single('audio'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const { duration, description } = req.body;
const { filename, size } = req.file;
const result = await pool.query(
'INSERT INTO recordings (filename, file_size, duration, description) VALUES ($1, $2, $3, $4) RETURNING *',
[filename, size, duration || null, description || null]
);
res.status(201).json({
message: 'Recording saved successfully',
recording: result.rows[0]
});
} catch (error) {
console.error('Error saving recording:', error);
res.status(500).json({ error: 'Failed to save recording' });
}
});
// Get specific recording
app.get('/api/recordings/:id', async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query('SELECT * FROM recordings WHERE id = $1', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Recording not found' });
}
res.json(result.rows[0]);
} catch (error) {
console.error('Error fetching recording:', error);
res.status(500).json({ error: 'Failed to fetch recording' });
}
});
// Download audio file
app.get('/api/download/:filename', (req, res) => {
try {
const { filename } = req.params;
const filepath = path.join(uploadsDir, filename);
res.download(filepath);
} catch (error) {
console.error('Error downloading file:', error);
res.status(500).json({ error: 'Failed to download file' });
}
});
// Delete recording
app.delete('/api/recordings/:id', async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query('SELECT filename FROM recordings WHERE id = $1', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Recording not found' });
}
const filename = result.rows[0].filename;
const filepath = path.join(uploadsDir, filename);
// Delete from database
await pool.query('DELETE FROM recordings WHERE id = $1', [id]);
// Delete file from disk
if (fs.existsSync(filepath)) {
fs.unlinkSync(filepath);
}
res.json({ message: 'Recording deleted successfully' });
} catch (error) {
console.error('Error deleting recording:', error);
res.status(500).json({ error: 'Failed to delete recording' });
}
});
// Start server
app.listen(PORT, async () => {
console.log(`Server running on http://localhost:${PORT}`);
await initializeDatabase();
});
// Graceful shutdown
process.on('SIGINT', async () => {
await pool.end();
process.exit(0);
});