-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-basic.js
More file actions
348 lines (290 loc) · 10.3 KB
/
server-basic.js
File metadata and controls
348 lines (290 loc) · 10.3 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
const express = require('express');
const multer = require('multer');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const { promisify } = require('util');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = process.env.PORT || 3000;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const { authenticateSimple, requireSimpleAuth } = require('./middleware/simpleAuth');
// Debug environment variables
console.log('Environment variables check:');
console.log('PORT:', PORT);
console.log('OPENAI_API_KEY:', OPENAI_API_KEY ? 'SET' : 'NOT SET');
console.log('ACCESS_PASSWORD:', process.env.ACCESS_PASSWORD ? 'SET' : 'NOT SET');
console.log('JWT_SECRET:', process.env.JWT_SECRET ? 'SET' : 'NOT SET');
console.log('NODE_ENV:', process.env.NODE_ENV || 'not set');
console.log('All environment variables:');
Object.keys(process.env).forEach(key => {
if (key.includes('API') || key.includes('PASSWORD') || key.includes('SECRET') || key.includes('NODE_ENV')) {
console.log(`${key}: ${process.env[key] ? 'SET' : 'NOT SET'}`);
}
});
const execAsync = promisify(exec);
// Basic middleware
app.use(express.json());
app.use(express.static('public'));
// CORS middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if (!fs.existsSync('uploads')) {
fs.mkdirSync('uploads', { recursive: true });
}
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
const timestamp = Date.now();
cb(null, `video_${timestamp}_${file.originalname}`);
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1500 * 1024 * 1024 // 1.5GB limit
}
});
// Simple auth functions
// Health check endpoint (public)
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
env: {
port: PORT,
hasOpenAI: !!OPENAI_API_KEY,
hasPassword: !!process.env.ACCESS_PASSWORD,
hasJWT: !!process.env.JWT_SECRET,
nodeEnv: process.env.NODE_ENV || 'not set'
}
});
});
// Debug endpoint to check environment variables (protected)
app.get('/debug/env', requireSimpleAuth, (req, res) => {
const envVars = {};
Object.keys(process.env).forEach(key => {
// Only show non-sensitive info
if (key.includes('PORT') || key.includes('NODE_ENV') || key.includes('RAILWAY')) {
envVars[key] = process.env[key];
} else if (key.includes('API') || key.includes('PASSWORD') || key.includes('SECRET')) {
envVars[key] = process.env[key] ? '***SET***' : 'NOT SET';
}
});
res.json({
environment: envVars,
processEnvKeys: Object.keys(process.env).length
});
});
// Simple authentication endpoint
app.post('/api/auth/simple', authenticateSimple);
// Authentication check endpoint
app.get('/api/auth/check', requireSimpleAuth, (req, res) => {
res.json({
authenticated: true,
timestamp: req.auth.timestamp
});
});
// Protected API routes
app.get('/api/server-files', requireSimpleAuth, (req, res) => {
try {
const uploadsDir = './uploads';
if (!fs.existsSync(uploadsDir)) {
return res.json({ files: [] });
}
const files = fs.readdirSync(uploadsDir)
.filter(file => {
const filePath = path.join(uploadsDir, file);
const stats = fs.statSync(filePath);
return stats.isFile() && /\.(mp4|avi|mov|wmv|mkv|webm|mp3|wav|m4a|aac|txt)$/i.test(file);
})
.map(file => {
const filePath = path.join(uploadsDir, file);
const stats = fs.statSync(filePath);
return {
name: file,
size: stats.size,
modified: stats.mtime.toISOString(),
isTranscription: file.includes('_transcription_')
};
})
.sort((a, b) => new Date(b.modified) - new Date(a.modified));
res.json({ files });
} catch (error) {
console.error('Error listing server files:', error);
res.status(500).json({ error: 'Failed to list server files' });
}
});
// Extract audio from video using FFmpeg
async function extractAudio(inputPath, outputPath) {
const command = `ffmpeg -i "${inputPath}" -vn -acodec mp3 -ab 64k -ac 1 -ar 22050 -y "${outputPath}"`;
console.log('Running FFmpeg command:', command);
try {
const { stdout, stderr } = await execAsync(command);
console.log('FFmpeg completed successfully');
return true;
} catch (error) {
console.error('FFmpeg error:', error);
throw new Error(`Audio extraction failed: ${error.message}`);
}
}
// Transcribe a single audio file
async function transcribeSingleFile(audioPath) {
const FormData = require('form-data');
const formData = new FormData();
const stats = fs.statSync(audioPath);
if (stats.size > 25 * 1024 * 1024) {
throw new Error(`File exceeds 25MB Whisper limit`);
}
formData.append('file', fs.createReadStream(audioPath), {
filename: path.basename(audioPath),
contentType: 'audio/mp3'
});
formData.append('model', 'whisper-1');
formData.append('response_format', 'json');
const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, {
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
...formData.getHeaders()
},
timeout: 600000
});
return response.data.text;
}
// Save transcription to file
function saveTranscriptionToFile(transcription, originalFilename) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const baseName = path.basename(originalFilename, path.extname(originalFilename));
const transcriptionFilename = `${baseName}_transcription_${timestamp}.txt`;
const transcriptionPath = path.join('uploads', transcriptionFilename);
const content = `Transcription for: ${originalFilename}\nGenerated: ${new Date().toISOString()}\n\n${transcription}`;
fs.writeFileSync(transcriptionPath, content, 'utf8');
return transcriptionFilename;
}
// Upload and transcribe endpoint (protected)
app.post('/api/transcribe', requireSimpleAuth, upload.single('file'), async (req, res) => {
if (!OPENAI_API_KEY) {
return res.status(500).json({ error: 'OpenAI API key not configured' });
}
let audioPath = null;
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
console.log(`Processing file: ${req.file.originalname}`);
const isAudio = req.file.mimetype.startsWith('audio/');
if (isAudio) {
audioPath = req.file.path;
} else {
audioPath = path.join('uploads', `server_audio_${Date.now()}.mp3`);
await extractAudio(req.file.path, audioPath);
}
const transcription = await transcribeSingleFile(audioPath);
const transcriptionFile = saveTranscriptionToFile(transcription, req.file.originalname);
res.json({
success: true,
message: 'Transcription completed',
transcription: transcription,
originalFile: req.file.filename,
transcriptionFile: transcriptionFile
});
} catch (error) {
console.error('Transcription error:', error);
res.status(500).json({
error: 'Transcription failed',
details: error.message
});
} finally {
// Clean up temporary audio file if it was extracted from video
if (audioPath && audioPath !== req.file?.path) {
try {
if (fs.existsSync(audioPath)) {
fs.unlinkSync(audioPath);
}
} catch (err) {
console.error('Cleanup error:', err);
}
}
}
});
// Process server file endpoint (protected)
app.post('/api/transcribe-server-file', requireSimpleAuth, async (req, res) => {
if (!OPENAI_API_KEY) {
return res.status(500).json({ error: 'OpenAI API key not configured' });
}
try {
const { filename } = req.body;
if (!filename) {
return res.status(400).json({ error: 'No filename provided' });
}
const filePath = path.join('uploads', filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const ext = path.extname(filename).toLowerCase();
const isAudio = ['.mp3', '.wav', '.m4a', '.aac'].includes(ext);
let audioPath = filePath;
let tempAudioPath = null;
if (!isAudio) {
tempAudioPath = path.join('uploads', `audio_${Date.now()}.mp3`);
await extractAudio(filePath, tempAudioPath);
audioPath = tempAudioPath;
}
const transcription = await transcribeSingleFile(audioPath);
const transcriptionFile = saveTranscriptionToFile(transcription, filename);
// Cleanup
if (tempAudioPath && fs.existsSync(tempAudioPath)) {
fs.unlinkSync(tempAudioPath);
}
res.json({
success: true,
message: 'Transcription completed',
transcription: transcription,
transcriptionFile: transcriptionFile
});
} catch (error) {
console.error('Server file transcription error:', error);
res.status(500).json({
error: 'Transcription failed',
details: error.message
});
}
});
// Download transcription endpoint (protected)
app.get('/api/download/:filename', requireSimpleAuth, (req, res) => {
const filename = req.params.filename;
const filePath = path.join('uploads', filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
res.download(filePath);
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Server error:', error);
res.status(500).json({ error: error.message });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`Health check: http://localhost:${PORT}/health`);
if (!OPENAI_API_KEY) {
console.warn('WARNING: OPENAI_API_KEY not set!');
}
if (!process.env.ACCESS_PASSWORD || process.env.ACCESS_PASSWORD === 'changeme') {
console.warn('WARNING: Using default ACCESS_PASSWORD. Please set a secure password!');
}
});