Spaces:
Running
Running
File size: 10,329 Bytes
ea81969 adbbc5e ea81969 adbbc5e ea81969 be25ec7 ea81969 |
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 |
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { exec } from 'child_process';
import { promisify } from 'util';
import fs from 'fs';
import path from 'path';
import { AIService } from '@/backend/services/ai';
import { AuthService } from '@/backend/services/authService';
import { CreditService } from '@/backend/services/creditService';
import { AdminService } from '@/backend/services/adminService';
const execPromise = promisify(exec);
dotenv.config();
const app = express();
// CRITICAL FIX: Increased limits to 100mb to allow processing of long audio/video base64 data
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: true }));
app.use(cors());
const apiRouter = express.Router();
apiRouter.post('/download', async (req, res) => {
const { url, quality, platform, sessionId, creditCost } = req.body;
try {
let eligibility = null;
// BYPASS LOGIC: Only check eligibility and deduct credits if NOT tiktok
if (platform !== 'tiktok') {
eligibility = await CreditService.checkEligibility(sessionId, null, 'downloader', false, creditCost);
} else {
console.log(`[DOWNLOADER] TikTok bypass triggered for URL: ${url}`);
}
const timestamp = Date.now();
const fileBaseName = `tm_dl_${timestamp}`;
const outputDir = '/tmp';
const extension = quality === 'audio' ? 'mp3' : 'mp4';
const outputPath = path.join(outputDir, `${fileBaseName}.${extension}`);
let formatStr = "";
if (quality === 'audio') {
formatStr = "-f 'ba' -x --audio-format mp3";
} else {
const qMap = {
'360p': 'bestvideo[height<=360]+bestaudio/best[height<=360]',
'720p': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
'1080p': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]'
};
const format = qMap[quality] || qMap['720p'];
formatStr = `-f "${format}" --merge-output-format mp4`;
}
const tiktokArgs = platform === 'tiktok' ? '--referer "https://www.tiktok.com/"' : '';
const command = `yt-dlp --no-playlist --no-warnings --no-check-certificate --js-runtime node ${formatStr} ${tiktokArgs} -o "${outputPath}" "${url.trim()}"`;
console.log(`[DOWNLOADER] Executing: ${command}`);
try {
await execPromise(command);
} catch (execErr) {
console.error("[DL-EXEC-FAIL]", execErr.stderr || execErr.message);
if (!fs.existsSync(outputPath)) {
throw new Error(`Engine Error: ${execErr.stderr || execErr.message}`);
}
}
if (!fs.existsSync(outputPath)) {
throw new Error("Download engine failed. File not generated.");
}
// Only commit deduction if eligibility was checked (non-tiktok)
if (eligibility) {
await CreditService.commitDeduction(eligibility);
}
res.download(outputPath, `${fileBaseName}.${extension}`, (err) => {
if (err) console.error("Stream Error:", err);
try {
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
} catch (e) { console.error("Cleanup Error:", e); }
});
} catch (error) {
console.error("[DOWNLOAD-ERROR]", error.message);
res.status(500).json({ error: error.message });
}
});
const handleAiRequest = async (req, res, toolKey, taskFn) => {
const sessionId = req.headers['x-session-id'];
const guestId = req.headers['x-guest-id'];
const { isOwnApi, customApiKey, creditCost } = req.body;
try {
const eligibility = await CreditService.checkEligibility(sessionId, guestId, toolKey, isOwnApi, creditCost);
const apiKey = isOwnApi ? (customApiKey || process.env.API_KEY) : process.env.API_KEY;
const result = await taskFn(apiKey, isOwnApi);
await CreditService.commitDeduction(eligibility);
res.json(result);
} catch (error) {
console.error(`[BACKEND-API] Error in ${toolKey}:`, error.message);
res.status(error.message.includes('REACHED') || error.message.includes('INSUFFICIENT') ? 403 : 500).json({
error: error.message
});
}
};
apiRouter.post('/transcribe', (req, res) => {
handleAiRequest(req, res, 'count_transcript', async (key, isOwn) => {
return { text: await AIService.transcribe(req.body.media, req.body.mimeType, key, isOwn) };
});
});
apiRouter.post('/recap', (req, res) => {
handleAiRequest(req, res, 'count_transcript', async (key, isOwn) => {
return { recap: await AIService.recap(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
});
});
apiRouter.post('/book-recap', (req, res) => {
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
return { recap: await AIService.bookRecap(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
});
});
apiRouter.post('/comic-translate', (req, res) => {
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
return { pdfData: await AIService.comicTranslate(req.body.media, req.body.mimeType, req.body.targetLanguage, key, isOwn) };
});
});
apiRouter.post('/translate', (req, res) => {
handleAiRequest(req, res, 'count_translate', async (key, isOwn) => {
return await AIService.translate(req.body.text, req.body.targetLanguage, req.body.options, key, isOwn);
});
});
apiRouter.post('/srt-translate', (req, res) => {
handleAiRequest(req, res, 'count_srt_translate', async (key, isOwn) => {
return { srt: await AIService.srtTranslate(req.body.srtContent, req.body.sourceLanguage, req.body.targetLanguage, key, isOwn) };
});
});
apiRouter.post('/tts', (req, res) => {
handleAiRequest(req, res, 'count_tts', async (key, isOwn) => {
return { audioData: await AIService.tts(req.body.text, req.body.voiceId, req.body.tone, key, isOwn) };
});
});
apiRouter.post('/subtitle', (req, res) => {
req.setTimeout(1200000);
handleAiRequest(req, res, 'count_subtitle', async (key, isOwn) => {
return await AIService.subtitle(
req.body.media,
req.body.mimeType,
req.body.script,
key,
isOwn,
req.body.sourceLanguage,
req.body.startOffsetMs || 0,
req.body.lastScriptIndex || 0
);
});
});
apiRouter.post('/content-creator', (req, res) => {
handleAiRequest(req, res, 'count_creator_text', async (key, isOwn) => {
const script = await AIService.contentCreator(
req.body.topic, req.body.category, req.body.subTopics,
req.body.contentType, req.body.creatorGender, req.body.targetLanguage, key, isOwn
);
let imageUrl = null;
if (req.body.withImage) {
try { imageUrl = await AIService.generateImage(req.body.topic, key, isOwn); } catch(e) {}
}
return { script, imageUrl };
});
});
apiRouter.post('/secure/save-key', async (req, res) => {
try {
const { sessionId, apiKey } = req.body;
res.json(await AuthService.saveCustomKey(sessionId, apiKey));
} catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/secure/update-session', async (req, res) => {
try {
const { userId, newSessionId } = req.body;
res.json(await AuthService.updateActiveSession(userId, newSessionId));
} catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/verify', async (req, res) => {
const { adminPassword } = req.body;
if (adminPassword === process.env.ADMIN_PASSWORD) res.json({ success: true });
else res.status(403).json({ error: "Unauthorized" });
});
apiRouter.post('/admin/update-settings', async (req, res) => {
const { adminPassword, settings } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.updateSettings(settings)); } catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/add-user', async (req, res) => {
const { adminPassword, userData, referrerCode } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.addUser(userData, referrerCode)); } catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/reactivate-user', async (req, res) => {
const { adminPassword, nodeKey, userClass, credits } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.reactivateUser(nodeKey, userClass, credits)); } catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/update-user-class', async (req, res) => {
const { adminPassword, nodeKey, userClass, credits } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.updateUserClass(nodeKey, userClass, credits)); } catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/topup-credits', async (req, res) => {
const { adminPassword, sessionId, amount } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.topUpCredits(sessionId, amount)); } catch (e) { res.status(500).json({ error: e.message }); }
});
apiRouter.post('/admin/delete-user', async (req, res) => {
const { adminPassword, nodeKey } = req.body;
if (adminPassword !== process.env.ADMIN_PASSWORD) return res.status(403).json({ error: "Denied" });
try { res.json(await AdminService.deleteUser(nodeKey)); } catch (e) { res.status(500).json({ error: e.message }); }
});
app.use('/', apiRouter);
const PORT = process.env.PORT || 7860;
app.listen(PORT, () => {
console.log(`🚀 Master Backend Engine running on port ${PORT}`);
});
|