Spaces:
Sleeping
Sleeping
Rename main.py to index.js
Browse files
index.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require("express");
|
| 2 |
+
const axios = require("axios");
|
| 3 |
+
const FormData = require("form-data");
|
| 4 |
+
const fs = require("fs");
|
| 5 |
+
const path = require("path");
|
| 6 |
+
|
| 7 |
+
const app = express();
|
| 8 |
+
const PORT = process.env.PORT || 3000;
|
| 9 |
+
|
| 10 |
+
app.use(express.urlencoded({ extended: true }));
|
| 11 |
+
app.use(express.json());
|
| 12 |
+
|
| 13 |
+
app.post("/upload", async (req, res) => {
|
| 14 |
+
const contentType = req.headers["content-type"];
|
| 15 |
+
if (!contentType || !contentType.startsWith("multipart/form-data")) {
|
| 16 |
+
return res.status(400).json({ error: "Content-Type must be multipart/form-data" });
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const boundary = contentType.split("boundary=")[1];
|
| 20 |
+
let data = Buffer.from([]);
|
| 21 |
+
req.on("data", chunk => data = Buffer.concat([data, chunk]));
|
| 22 |
+
req.on("end", async () => {
|
| 23 |
+
const parts = data.toString().split(`--${boundary}`);
|
| 24 |
+
const filePart = parts.find(p => p.includes("filename="));
|
| 25 |
+
if (!filePart) return res.status(400).json({ error: "No file uploaded" });
|
| 26 |
+
|
| 27 |
+
const filenameMatch = filePart.match(/filename="(.+?)"/);
|
| 28 |
+
const filename = filenameMatch ? filenameMatch[1] : `file_${Date.now()}`;
|
| 29 |
+
const ext = path.extname(filename);
|
| 30 |
+
const timestamp = Date.now();
|
| 31 |
+
const finalName = `${timestamp}${ext}`;
|
| 32 |
+
const contentIndex = filePart.indexOf("\r\n\r\n") + 4;
|
| 33 |
+
const fileContent = filePart.substring(contentIndex, filePart.lastIndexOf("\r\n"));
|
| 34 |
+
const buffer = Buffer.from(fileContent, "binary");
|
| 35 |
+
const savePath = path.join(__dirname, "uploads", finalName);
|
| 36 |
+
if (!fs.existsSync(path.join(__dirname, "uploads"))) fs.mkdirSync(path.join(__dirname, "uploads"));
|
| 37 |
+
|
| 38 |
+
fs.writeFileSync(savePath, buffer);
|
| 39 |
+
|
| 40 |
+
const form = new FormData();
|
| 41 |
+
form.append("reqtype", "fileupload");
|
| 42 |
+
form.append("userhash", "");
|
| 43 |
+
form.append("fileToUpload", fs.createReadStream(savePath));
|
| 44 |
+
|
| 45 |
+
try {
|
| 46 |
+
const uploadResponse = await axios.post("https://catbox.moe/user/api.php", form, {
|
| 47 |
+
headers: {
|
| 48 |
+
...form.getHeaders(),
|
| 49 |
+
"User-Agent": "Mozilla/5.0",
|
| 50 |
+
"Accept": "application/json",
|
| 51 |
+
"Accept-Encoding": "gzip, deflate, br, zstd",
|
| 52 |
+
"sec-ch-ua-platform": '"Android"',
|
| 53 |
+
"cache-control": "no-cache",
|
| 54 |
+
"sec-ch-ua": '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
|
| 55 |
+
"sec-ch-ua-mobile": "?1",
|
| 56 |
+
"x-requested-with": "XMLHttpRequest",
|
| 57 |
+
"dnt": "1",
|
| 58 |
+
"origin": "https://catbox.moe",
|
| 59 |
+
"sec-fetch-site": "same-origin",
|
| 60 |
+
"sec-fetch-mode": "cors",
|
| 61 |
+
"sec-fetch-dest": "empty",
|
| 62 |
+
"referer": "https://catbox.moe/",
|
| 63 |
+
"accept-language": "en-US,en;q=0.9",
|
| 64 |
+
"priority": "u=1, i"
|
| 65 |
+
}
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
fs.unlinkSync(savePath);
|
| 69 |
+
res.json({ fileUrl: uploadResponse.data });
|
| 70 |
+
} catch (err) {
|
| 71 |
+
res.status(500).json({ error: "Failed to upload to Catbox", details: err.message });
|
| 72 |
+
}
|
| 73 |
+
});
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|
main.py
DELETED
|
@@ -1,99 +0,0 @@
|
|
| 1 |
-
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 2 |
-
from urllib.parse import urlparse, parse_qs
|
| 3 |
-
import subprocess
|
| 4 |
-
import os
|
| 5 |
-
import json
|
| 6 |
-
import time
|
| 7 |
-
import threading
|
| 8 |
-
|
| 9 |
-
PORT = 7860
|
| 10 |
-
DOWNLOAD_DIR = "downloads"
|
| 11 |
-
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 12 |
-
|
| 13 |
-
def delete_after(filepath, delay):
|
| 14 |
-
def delete():
|
| 15 |
-
time.sleep(delay)
|
| 16 |
-
if os.path.exists(filepath):
|
| 17 |
-
os.remove(filepath)
|
| 18 |
-
print(f"[AUTO DELETE] Removed {filepath}")
|
| 19 |
-
threading.Thread(target=delete, daemon=True).start()
|
| 20 |
-
|
| 21 |
-
class SpotDLServer(BaseHTTPRequestHandler):
|
| 22 |
-
def do_GET(self):
|
| 23 |
-
parsed = urlparse(self.path)
|
| 24 |
-
|
| 25 |
-
if parsed.path == "/sptdl":
|
| 26 |
-
query = parse_qs(parsed.query)
|
| 27 |
-
url = query.get("url", [None])[0]
|
| 28 |
-
|
| 29 |
-
if not url:
|
| 30 |
-
self.respond_json({"error": "Missing 'url' parameter"})
|
| 31 |
-
return
|
| 32 |
-
|
| 33 |
-
timestamp = str(int(time.time()))
|
| 34 |
-
print(f"[REQUEST] Spotify URL: {url}")
|
| 35 |
-
|
| 36 |
-
before_files = set(os.listdir(DOWNLOAD_DIR))
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
subprocess.run(
|
| 40 |
-
["spotdl", url, "--output", f"{DOWNLOAD_DIR}/%(title)s.%(ext)s"],
|
| 41 |
-
check=True,
|
| 42 |
-
stdout=subprocess.DEVNULL,
|
| 43 |
-
stderr=subprocess.DEVNULL
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
after_files = set(os.listdir(DOWNLOAD_DIR))
|
| 47 |
-
new_files = list(after_files - before_files)
|
| 48 |
-
if not new_files:
|
| 49 |
-
raise Exception("No file downloaded")
|
| 50 |
-
|
| 51 |
-
original_file = new_files[0]
|
| 52 |
-
original_path = os.path.join(DOWNLOAD_DIR, original_file)
|
| 53 |
-
renamed_path = os.path.join(DOWNLOAD_DIR, f"{timestamp}.mp3")
|
| 54 |
-
|
| 55 |
-
os.rename(original_path, renamed_path)
|
| 56 |
-
|
| 57 |
-
real_title = os.path.splitext(original_file)[0]
|
| 58 |
-
host = self.headers.get("Host")
|
| 59 |
-
download_url = f"http://{host}/{renamed_path}"
|
| 60 |
-
|
| 61 |
-
print(f"[SUCCESS] Downloaded: {real_title}")
|
| 62 |
-
print(f"[SAVED AS] {timestamp}.mp3")
|
| 63 |
-
|
| 64 |
-
delete_after(renamed_path, 120)
|
| 65 |
-
|
| 66 |
-
self.respond_json({
|
| 67 |
-
"title": real_title,
|
| 68 |
-
"download_link": download_url
|
| 69 |
-
})
|
| 70 |
-
|
| 71 |
-
except Exception as e:
|
| 72 |
-
print(f"[ERROR] {str(e)}")
|
| 73 |
-
self.respond_json({"error": str(e)})
|
| 74 |
-
|
| 75 |
-
elif self.path.startswith(f"/{DOWNLOAD_DIR}/"):
|
| 76 |
-
file_path = self.path.lstrip("/")
|
| 77 |
-
if os.path.isfile(file_path):
|
| 78 |
-
with open(file_path, "rb") as f:
|
| 79 |
-
self.send_response(200)
|
| 80 |
-
self.send_header("Content-Type", "audio/mpeg")
|
| 81 |
-
self.end_headers()
|
| 82 |
-
self.wfile.write(f.read())
|
| 83 |
-
else:
|
| 84 |
-
self.send_error(404, "File not found.")
|
| 85 |
-
else:
|
| 86 |
-
self.send_error(404, "Invalid endpoint.")
|
| 87 |
-
|
| 88 |
-
def respond_json(self, data):
|
| 89 |
-
self.send_response(200)
|
| 90 |
-
self.send_header("Content-Type", "application/json")
|
| 91 |
-
self.end_headers()
|
| 92 |
-
self.wfile.write(json.dumps(data).encode())
|
| 93 |
-
|
| 94 |
-
def run_server():
|
| 95 |
-
print(f"[SERVER] SpotDL server running at http://0.0.0.0:{PORT}")
|
| 96 |
-
HTTPServer(("0.0.0.0", PORT), SpotDLServer).serve_forever()
|
| 97 |
-
|
| 98 |
-
if __name__ == "__main__":
|
| 99 |
-
run_server()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|