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+
const express = require('express');
|
| 2 |
+
const cors = require('cors');
|
| 3 |
+
const fetch = require('node-fetch');
|
| 4 |
+
const bodyParser = require('body-parser');
|
| 5 |
+
|
| 6 |
+
const app = express();
|
| 7 |
+
const PORT = 7860; // Default port for Hugging Face Spaces
|
| 8 |
+
|
| 9 |
+
// --- CONFIGURATION ---
|
| 10 |
+
// These tokens must be set in your Space Settings -> Variables and secrets
|
| 11 |
+
const STORAGE_POOLS = [
|
| 12 |
+
{
|
| 13 |
+
repo: "abhy60098/MY-STORAGE",
|
| 14 |
+
token: process.env.HF_TOKEN_1
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
repo: "sushmasinharnc/MY-STORAGE",
|
| 18 |
+
token: process.env.HF_TOKEN_2
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
repo: "shuarya2011/MY-STORAGE",
|
| 22 |
+
token: process.env.HF_TOKEN_3
|
| 23 |
+
}
|
| 24 |
+
];
|
| 25 |
+
|
| 26 |
+
const DB_FILE = "db.json";
|
| 27 |
+
|
| 28 |
+
// --- MIDDLEWARE ---
|
| 29 |
+
app.use(cors()); // Allows any website to connect
|
| 30 |
+
app.use(bodyParser.json({ limit: '50mb' })); // Allows large image uploads
|
| 31 |
+
|
| 32 |
+
// --- ROUTES ---
|
| 33 |
+
|
| 34 |
+
// 1. Health Check / Home Page
|
| 35 |
+
app.get('/', (req, res) => {
|
| 36 |
+
res.send(`
|
| 37 |
+
<div style="font-family: sans-serif; text-align: center; margin-top: 50px;">
|
| 38 |
+
<h1>🚀 Distributed Storage API is Online</h1>
|
| 39 |
+
<p>Status: <b>Connected to ${STORAGE_POOLS.length} Storage Pools</b></p>
|
| 40 |
+
<p>Use <code>/posts</code> (GET) to fetch data and <code>/posts</code> (POST) to upload.</p>
|
| 41 |
+
</div>
|
| 42 |
+
`);
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
// 2. GET: Fetch data from all 3 datasets and merge them
|
| 46 |
+
app.get('/posts', async (req, res) => {
|
| 47 |
+
try {
|
| 48 |
+
const allResults = await Promise.all(STORAGE_POOLS.map(async (pool) => {
|
| 49 |
+
// We check if the token exists before calling
|
| 50 |
+
if (!pool.token) return [];
|
| 51 |
+
|
| 52 |
+
const url = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
|
| 53 |
+
const response = await fetch(url, {
|
| 54 |
+
headers: { Authorization: `Bearer ${pool.token}` }
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
if (response.ok) {
|
| 58 |
+
const data = await response.json();
|
| 59 |
+
return data.posts || [];
|
| 60 |
+
}
|
| 61 |
+
return []; // Return empty if file doesn't exist yet
|
| 62 |
+
}));
|
| 63 |
+
|
| 64 |
+
// Flatten the array of arrays and sort by ID (timestamp) descending
|
| 65 |
+
const mergedPosts = allResults.flat().sort((a, b) => b.id - a.id);
|
| 66 |
+
res.json(mergedPosts);
|
| 67 |
+
} catch (err) {
|
| 68 |
+
console.error("GET Error:", err);
|
| 69 |
+
res.status(500).json({ error: "Failed to fetch posts from pools." });
|
| 70 |
+
}
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
// 3. POST: Upload image and update database in a random pool
|
| 74 |
+
app.post('/posts', async (req, res) => {
|
| 75 |
+
try {
|
| 76 |
+
const { username, caption, imageBase64, fileName } = req.body;
|
| 77 |
+
|
| 78 |
+
if (!imageBase64 || !username) {
|
| 79 |
+
return res.status(400).json({ error: "Missing required fields (username or image)." });
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Pick a random pool to distribute storage usage
|
| 83 |
+
const pool = STORAGE_POOLS[Math.floor(Math.random() * STORAGE_POOLS.length)];
|
| 84 |
+
|
| 85 |
+
if (!pool.token) {
|
| 86 |
+
return res.status(500).json({ error: "Storage pool token not configured in Secrets." });
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
const timestamp = Date.now();
|
| 90 |
+
const imagePath = `uploads/${timestamp}-${fileName}`;
|
| 91 |
+
|
| 92 |
+
// A. Upload the Image file
|
| 93 |
+
const uploadImageUrl = `https://huggingface.co/api/datasets/${pool.repo}/upload/main/${imagePath}`;
|
| 94 |
+
const imageUploadRes = await fetch(uploadImageUrl, {
|
| 95 |
+
method: 'POST',
|
| 96 |
+
headers: {
|
| 97 |
+
Authorization: `Bearer ${pool.token}`,
|
| 98 |
+
'Content-Type': 'application/json'
|
| 99 |
+
},
|
| 100 |
+
body: JSON.stringify({
|
| 101 |
+
content: imageBase64, // Expecting raw base64 string
|
| 102 |
+
message: `Upload image from ${username}`
|
| 103 |
+
})
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
if (!imageUploadRes.ok) {
|
| 107 |
+
const errorText = await imageUploadRes.text();
|
| 108 |
+
throw new Error(`Image Upload Failed: ${errorText}`);
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const finalImageUrl = `https://huggingface.co/datasets/${pool.repo}/resolve/main/${imagePath}`;
|
| 112 |
+
|
| 113 |
+
// B. Fetch existing db.json from the SAME pool
|
| 114 |
+
const dbUrl = `https://huggingface.co/api/datasets/${pool.repo}/raw/main/${DB_FILE}`;
|
| 115 |
+
const dbRes = await fetch(dbUrl, {
|
| 116 |
+
headers: { Authorization: `Bearer ${pool.token}` }
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
let db = { posts: [] };
|
| 120 |
+
if (dbRes.ok) {
|
| 121 |
+
db = await dbRes.json();
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
// C. Add new post to the beginning of the list
|
| 125 |
+
db.posts.unshift({
|
| 126 |
+
id: timestamp,
|
| 127 |
+
username,
|
| 128 |
+
caption,
|
| 129 |
+
imageUrl: finalImageUrl,
|
| 130 |
+
pool: pool.repo
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
// D. Upload the updated db.json back to Hugging Face
|
| 134 |
+
const updateDbUrl = `https://huggingface.co/api/datasets/${pool.repo}/upload/main/${DB_FILE}`;
|
| 135 |
+
const dbUploadRes = await fetch(updateDbUrl, {
|
| 136 |
+
method: 'POST',
|
| 137 |
+
headers: {
|
| 138 |
+
Authorization: `Bearer ${pool.token}`,
|
| 139 |
+
'Content-Type': 'application/json'
|
| 140 |
+
},
|
| 141 |
+
body: JSON.stringify({
|
| 142 |
+
content: Buffer.from(JSON.stringify(db, null, 2)).toString('base64'),
|
| 143 |
+
message: "Update database JSON"
|
| 144 |
+
})
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
if (!dbUploadRes.ok) throw new Error("Database update failed.");
|
| 148 |
+
|
| 149 |
+
res.status(201).json({ success: true, imageUrl: finalImageUrl });
|
| 150 |
+
} catch (err) {
|
| 151 |
+
console.error("POST Error:", err);
|
| 152 |
+
res.status(500).json({ error: err.message });
|
| 153 |
+
}
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
// Start the server
|
| 157 |
+
app.listen(PORT, () => {
|
| 158 |
+
console.log(`Server is running on http://localhost:${PORT}`);
|
| 159 |
+
});
|