Spaces:
Running
Running
Delete server.js
Browse files
server.js
DELETED
|
@@ -1,244 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import express from 'express';
|
| 3 |
-
import cors from 'cors';
|
| 4 |
-
import dotenv from 'dotenv';
|
| 5 |
-
import { exec } from 'child_process';
|
| 6 |
-
import { promisify } from 'util';
|
| 7 |
-
import fs from 'fs';
|
| 8 |
-
import path from 'path';
|
| 9 |
-
import { AIService } from '@/backend/services/ai';
|
| 10 |
-
import { AuthService } from '@/backend/services/authService';
|
| 11 |
-
import { CreditService } from '@/backend/services/creditService';
|
| 12 |
-
import { AdminService } from '@/backend/services/adminService';
|
| 13 |
-
|
| 14 |
-
const execPromise = promisify(exec);
|
| 15 |
-
dotenv.config();
|
| 16 |
-
|
| 17 |
-
const app = express();
|
| 18 |
-
|
| 19 |
-
// CRITICAL FIX: Increased limits to 100mb to allow processing of long audio/video base64 data
|
| 20 |
-
app.use(express.json({ limit: '100mb' }));
|
| 21 |
-
app.use(express.urlencoded({ limit: '100mb', extended: true }));
|
| 22 |
-
|
| 23 |
-
app.use(cors());
|
| 24 |
-
|
| 25 |
-
const apiRouter = express.Router();
|
| 26 |
-
|
| 27 |
-
apiRouter.post('/download', async (req, res) => {
|
| 28 |
-
const { url, quality, platform, sessionId, creditCost } = req.body;
|
| 29 |
-
|
| 30 |
-
try {
|
| 31 |
-
const eligibility = await CreditService.checkEligibility(sessionId, null, 'downloader', false, creditCost);
|
| 32 |
-
|
| 33 |
-
const timestamp = Date.now();
|
| 34 |
-
const fileBaseName = `tm_dl_${timestamp}`;
|
| 35 |
-
const outputDir = '/tmp';
|
| 36 |
-
|
| 37 |
-
// Determine file extension and format string
|
| 38 |
-
const extension = quality === 'audio' ? 'mp3' : 'mp4';
|
| 39 |
-
const outputPath = path.join(outputDir, `${fileBaseName}.${extension}`);
|
| 40 |
-
|
| 41 |
-
let formatStr = "";
|
| 42 |
-
if (quality === 'audio') {
|
| 43 |
-
formatStr = "-f 'ba' -x --audio-format mp3";
|
| 44 |
-
} else {
|
| 45 |
-
const qMap = {
|
| 46 |
-
'360p': 'bestvideo[height<=360]+bestaudio/best[height<=360]',
|
| 47 |
-
'720p': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
|
| 48 |
-
'1080p': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]'
|
| 49 |
-
};
|
| 50 |
-
const format = qMap[quality] || qMap['720p'];
|
| 51 |
-
formatStr = `-f "${format}" --merge-output-format mp4`;
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
const tiktokArgs = platform === 'tiktok' ? '--referer "https://www.tiktok.com/"' : '';
|
| 55 |
-
|
| 56 |
-
// CRITICAL FIX: Added --js-runtime node to fix JS engine missing error.
|
| 57 |
-
// Added --no-warnings and --no-check-certificate for better reliability on Cloud Run.
|
| 58 |
-
const command = `yt-dlp --no-playlist --no-warnings --no-check-certificate --js-runtime node ${formatStr} ${tiktokArgs} -o "${outputPath}" "${url.trim()}"`;
|
| 59 |
-
|
| 60 |
-
console.log(`[DOWNLOADER] Executing: ${command}`);
|
| 61 |
-
|
| 62 |
-
try {
|
| 63 |
-
await execPromise(command);
|
| 64 |
-
} catch (execErr) {
|
| 65 |
-
console.error("[DL-EXEC-FAIL]", execErr.stderr || execErr.message);
|
| 66 |
-
// Even if warnings are printed to stderr, check if file exists before crashing
|
| 67 |
-
if (!fs.existsSync(outputPath)) {
|
| 68 |
-
throw new Error(`Engine Error: ${execErr.stderr || execErr.message}`);
|
| 69 |
-
}
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
// Verify file existence explicitly
|
| 73 |
-
if (!fs.existsSync(outputPath)) {
|
| 74 |
-
throw new Error("Download engine failed. File not generated.");
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
await CreditService.commitDeduction(eligibility);
|
| 78 |
-
|
| 79 |
-
res.download(outputPath, `${fileBaseName}.${extension}`, (err) => {
|
| 80 |
-
if (err) console.error("Stream Error:", err);
|
| 81 |
-
try {
|
| 82 |
-
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
|
| 83 |
-
} catch (e) { console.error("Cleanup Error:", e); }
|
| 84 |
-
});
|
| 85 |
-
|
| 86 |
-
} catch (error) {
|
| 87 |
-
console.error("[DOWNLOAD-ERROR]", error.message);
|
| 88 |
-
res.status(500).json({ error: error.message });
|
| 89 |
-
}
|
| 90 |
-
});
|
| 91 |
-
|
| 92 |
-
const handleAiRequest = async (req, res, toolKey, taskFn) => {
|
| 93 |
-
const sessionId = req.headers['x-session-id'];
|
| 94 |
-
const guestId = req.headers['x-guest-id'];
|
| 95 |
-
const { isOwnApi, customApiKey, creditCost } = req.body;
|
| 96 |
-
|
| 97 |
-
try {
|
| 98 |
-
const eligibility = await CreditService.checkEligibility(sessionId, guestId, toolKey, isOwnApi, creditCost);
|
| 99 |
-
const apiKey = isOwnApi ? (customApiKey || process.env.API_KEY) : process.env.API_KEY;
|
| 100 |
-
const result = await taskFn(apiKey, isOwnApi);
|
| 101 |
-
await CreditService.commitDeduction(eligibility);
|
| 102 |
-
res.json(result);
|
| 103 |
-
} catch (error) {
|
| 104 |
-
console.error(`[BACKEND-API] Error in ${toolKey}:`, error.message);
|
| 105 |
-
res.status(error.message.includes('REACHED') || error.message.includes('INSUFFICIENT') ? 403 : 500).json({
|
| 106 |
-
error: error.message
|
| 107 |
-
});
|
| 108 |
-
}
|
| 109 |
-
};
|
| 110 |
-
|
| 111 |
-
apiRouter.post('/transcribe', (req, res) => {
|
| 112 |
-
handleAiRequest(req, res, 'count_transcript', async (key, isOwn) => {
|
| 113 |
-
return { text: await AIService.transcribe(req.body.media, req.body.mimeType, key, isOwn) };
|
| 114 |
-
});
|
| 115 |
-
});
|
| 116 |
-
|
| 117 |
-
apiRouter.post('/recap', (req, res) => {
|
| 118 |
-
handleAiRequest(req, res, 'count_transcript', async (key, isOwn) => {
|
| 119 |
-
return { recap: await AIService.recap(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
|
| 120 |
-
});
|
| 121 |
-
});
|
| 122 |
-
|
| 123 |
-
apiRouter.post('/book-recap', (req, res) => {
|
| 124 |
-
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
|
| 125 |
-
return { recap: await AIService.bookRecap(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
|
| 126 |
-
});
|
| 127 |
-
});
|
| 128 |
-
|
| 129 |
-
apiRouter.post('/comic-translate', (req, res) => {
|
| 130 |
-
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
|
| 131 |
-
return { pdfData: await AIService.comicTranslate(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
|
| 132 |
-
});
|
| 133 |
-
});
|
| 134 |
-
|
| 135 |
-
apiRouter.post('/translate', (req, res) => {
|
| 136 |
-
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
|
| 137 |
-
return await AIService.translate(req.body.text, req.body.targetLanguage, req.body.options, key, isOwn);
|
| 138 |
-
});
|
| 139 |
-
});
|
| 140 |
-
|
| 141 |
-
apiRouter.post('/srt-translate', (req, res) => {
|
| 142 |
-
handleAiRequest(req, res, 'count_srt_translate', async (key, isOwn) => {
|
| 143 |
-
return { srt: await AIService.srtTranslate(req.body.srtContent, req.body.sourceLanguage, req.body.targetLanguage, key, isOwn) };
|
| 144 |
-
});
|
| 145 |
-
});
|
| 146 |
-
|
| 147 |
-
apiRouter.post('/tts', (req, res) => {
|
| 148 |
-
handleAiRequest(req, res, 'count_tts', async (key, isOwn) => {
|
| 149 |
-
return { audioData: await AIService.tts(req.body.text, req.body.voiceId, req.body.tone, key, isOwn) };
|
| 150 |
-
});
|
| 151 |
-
});
|
| 152 |
-
|
| 153 |
-
apiRouter.post('/subtitle', (req, res) => {
|
| 154 |
-
req.setTimeout(1200000);
|
| 155 |
-
handleAiRequest(req, res, 'count_subtitle', async (key, isOwn) => {
|
| 156 |
-
return await AIService.subtitle(
|
| 157 |
-
req.body.media,
|
| 158 |
-
req.body.mimeType,
|
| 159 |
-
req.body.script,
|
| 160 |
-
key,
|
| 161 |
-
isOwn,
|
| 162 |
-
req.body.sourceLanguage,
|
| 163 |
-
req.body.startOffsetMs || 0,
|
| 164 |
-
req.body.lastScriptIndex || 0
|
| 165 |
-
);
|
| 166 |
-
});
|
| 167 |
-
});
|
| 168 |
-
|
| 169 |
-
apiRouter.post('/content-creator', (req, res) => {
|
| 170 |
-
handleAiRequest(req, res, 'count_creator_text', async (key, isOwn) => {
|
| 171 |
-
const script = await AIService.contentCreator(
|
| 172 |
-
req.body.topic, req.body.category, req.body.subTopics,
|
| 173 |
-
req.body.contentType, req.body.creatorGender, req.body.targetLanguage, key, isOwn
|
| 174 |
-
);
|
| 175 |
-
let imageUrl = null;
|
| 176 |
-
if (req.body.withImage) {
|
| 177 |
-
try { imageUrl = await AIService.generateImage(req.body.topic, key, isOwn); } catch(e) {}
|
| 178 |
-
}
|
| 179 |
-
return { script, imageUrl };
|
| 180 |
-
});
|
| 181 |
-
});
|
| 182 |
-
|
| 183 |
-
apiRouter.post('/secure/save-key', async (req, res) => {
|
| 184 |
-
try {
|
| 185 |
-
const { sessionId, apiKey } = req.body;
|
| 186 |
-
res.json(await AuthService.saveCustomKey(sessionId, apiKey));
|
| 187 |
-
} catch (e) { res.status(500).json({ error: e.message }); }
|
| 188 |
-
});
|
| 189 |
-
|
| 190 |
-
apiRouter.post('/secure/update-session', async (req, res) => {
|
| 191 |
-
try {
|
| 192 |
-
const { userId, newSessionId } = req.body;
|
| 193 |
-
res.json(await AuthService.updateActiveSession(userId, newSessionId));
|
| 194 |
-
} catch (e) { res.status(500).json({ error: e.message }); }
|
| 195 |
-
});
|
| 196 |
-
|
| 197 |
-
apiRouter.post('/admin/verify', async (req, res) => {
|
| 198 |
-
const { adminPassword } = req.body;
|
| 199 |
-
if (adminPassword === process.env.ADMIN_PASSWORD) res.json({ success: true });
|
| 200 |
-
else res.status(403).json({ error: "Unauthorized" });
|
| 201 |
-
});
|
| 202 |
-
|
| 203 |
-
apiRouter.post('/admin/update-settings', async (req, res) => {
|
| 204 |
-
const { adminPassword, settings } = req.body;
|
| 205 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 206 |
-
try { res.json(await AdminService.updateSettings(settings)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 207 |
-
});
|
| 208 |
-
|
| 209 |
-
apiRouter.post('/admin/add-user', async (req, res) => {
|
| 210 |
-
const { adminPassword, userData, referrerCode } = req.body;
|
| 211 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 212 |
-
try { res.json(await AdminService.addUser(userData, referrerCode)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 213 |
-
});
|
| 214 |
-
|
| 215 |
-
apiRouter.post('/admin/reactivate-user', async (req, res) => {
|
| 216 |
-
const { adminPassword, nodeKey, userClass, credits } = req.body;
|
| 217 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 218 |
-
try { res.json(await AdminService.reactivateUser(nodeKey, userClass, credits)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 219 |
-
});
|
| 220 |
-
|
| 221 |
-
apiRouter.post('/admin/update-user-class', async (req, res) => {
|
| 222 |
-
const { adminPassword, nodeKey, userClass, credits } = req.body;
|
| 223 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 224 |
-
try { res.json(await AdminService.updateUserClass(nodeKey, userClass, credits)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 225 |
-
});
|
| 226 |
-
|
| 227 |
-
apiRouter.post('/admin/topup-credits', async (req, res) => {
|
| 228 |
-
const { adminPassword, sessionId, amount } = req.body;
|
| 229 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 230 |
-
try { res.json(await AdminService.topUpCredits(sessionId, amount)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 231 |
-
});
|
| 232 |
-
|
| 233 |
-
apiRouter.post('/admin/delete-user', async (req, res) => {
|
| 234 |
-
const { adminPassword, nodeKey } = req.body;
|
| 235 |
-
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
|
| 236 |
-
try { res.json(await AdminService.deleteUser(nodeKey)); } catch (e) { res.status(500).json({ error: e.message }); }
|
| 237 |
-
});
|
| 238 |
-
|
| 239 |
-
app.use('/', apiRouter);
|
| 240 |
-
|
| 241 |
-
const PORT = process.env.PORT || 7860;
|
| 242 |
-
app.listen(PORT, () => {
|
| 243 |
-
console.log(`🚀 Master Backend Engine running on port ${PORT}`);
|
| 244 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|