64 lines
2.0 KiB
JavaScript
64 lines
2.0 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 80;
|
|
|
|
app.use(express.json());
|
|
app.use(express.static(__dirname));
|
|
|
|
// Endpoint to add a stream from the frontend
|
|
app.post('/api/streams', (req, res) => {
|
|
const { name, embedCode } = req.body;
|
|
if (!name || !embedCode) {
|
|
return res.status(400).json({ error: 'Name and embed code are required.' });
|
|
}
|
|
|
|
// Extract URL from embedCode
|
|
// Supports iframe elements (searches for src attribute) and raw URLs
|
|
let url = '';
|
|
const srcMatch = embedCode.match(/src=["']([^"']+)["']/i);
|
|
if (srcMatch) {
|
|
url = srcMatch[1];
|
|
} else {
|
|
const trimmed = embedCode.trim();
|
|
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
|
url = trimmed;
|
|
} else {
|
|
return res.status(400).json({ error: 'Invalid input. Please provide a valid iframe embed code or raw URL.' });
|
|
}
|
|
}
|
|
|
|
// Clean name and url
|
|
const cleanName = name.trim();
|
|
const cleanUrl = url.trim();
|
|
|
|
if (!cleanName || !cleanUrl) {
|
|
return res.status(400).json({ error: 'Name and URL cannot be empty.' });
|
|
}
|
|
|
|
// Read the file to see if a newline is needed at the end
|
|
const filePath = path.join(__dirname, 'streams.txt');
|
|
fs.readFile(filePath, 'utf8', (err, data) => {
|
|
let prefix = '';
|
|
if (!err && data.length > 0 && !data.endsWith('\n')) {
|
|
prefix = '\n';
|
|
}
|
|
|
|
const newline = `${prefix}${cleanName}, ${cleanUrl}\n`;
|
|
|
|
fs.appendFile(filePath, newline, 'utf8', (writeErr) => {
|
|
if (writeErr) {
|
|
console.error('File write error:', writeErr);
|
|
return res.status(500).json({ error: 'Failed to write to streams.txt' });
|
|
}
|
|
res.json({ success: true, name: cleanName, url: cleanUrl });
|
|
});
|
|
});
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server listening on port ${PORT}`);
|
|
});
|