File size: 8,815 Bytes
fe02ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// server.js  — one‑vote‑per‑IP edition
const express     = require('express');
const bodyParser  = require('body-parser');
const fs          = require('fs');
const path        = require('path');
const requestIp   = require('request-ip');       // NEW
const crypto      = require('crypto');           // we'll hash IPs before saving
const archiver    = require('./leaderboard_archiver');
const https       = require('https');            // For Hugging Face API requests

const PORT         = process.env.PORT || 3000;
const DATA_FILE    = path.join(__dirname, 'data', 'data.json');
const IP_FILE      = path.join(__dirname, 'data', 'ips.json');

const CATEGORIES = ["6gb", "12gb", "16gb", "24gb", "48gb", "72gb", "96gb"];
function validateCategory(cat) {
  return CATEGORIES.includes(cat);
}

const app = express();
app.use(bodyParser.json());
app.use(requestIp.mw());                         // adds req.clientIp
app.use(express.static(path.join(__dirname, 'public')));

/* ---------- tiny helpers ---------- */
function readJson(file, fallback) {
  try { return JSON.parse(fs.readFileSync(file)); }
  catch { return fallback; }
}
function writeJson(file, obj) {
  fs.writeFileSync(file, JSON.stringify(obj, null, 2));
}
function hash(ip) {                              // do not store raw IP
  return crypto.createHash('sha256').update(ip).digest('hex');
}

/* ---------- IP‑limit middleware ---------- */
function oneVotePerIP(req, res, next) {
  const ipList = readJson(IP_FILE, {});
  const key    = hash(req.clientIp || 'unknown');
  if (ipList[key]) return res.status(409)
    .json({ error: 'You have already voted from this IP' });
  req._ipKey = key;          // remember for later
  next();
}

/* ---------- Ensure IP tracking is properly formatted ---------- */
function ensureValidIpTracking() {
  const ips = readJson(IP_FILE, {});
  let changed = false;
  
  // Convert any string values to objects
  Object.keys(ips).forEach(key => {
    if (typeof ips[key] === 'string') {
      ips[key] = {};
      changed = true;
    }
  });
  
  if (changed) {
    writeJson(IP_FILE, ips);
  }
  
  return ips;
}

/* ---------- API ---------- */
app.get('/api/entries', (req, res) => {
  const category = req.query.category;
  const data = readJson(DATA_FILE, {});
  if (!validateCategory(category)) {
    return res.status(400).json({ error: 'Invalid category' });
  }
  const entries = (data[category] || []).sort((a, b) => b.votes - a.votes);
  res.json(entries);
});

/*  Add new entry + cast initial vote  */
app.post('/api/add', (req, res) => {
  const name = (req.body.name || '').trim();
  const category = req.body.category;
  if (!name) return res.status(400).json({ error: 'Name required' });
  if (!validateCategory(category)) return res.status(400).json({ error: 'Invalid category' });

  const data = readJson(DATA_FILE, {});
  const list = data[category] = data[category] || [];
  if (list.find(e => e.name.toLowerCase() === name.toLowerCase()))
    return res.status(400).json({ error: 'Entry already exists' });

  const ips = ensureValidIpTracking();
  const ipKey = hash(req.clientIp || 'unknown');
  if (!ips[ipKey] || typeof ips[ipKey] !== 'object') ips[ipKey] = {};
  const prevVotedId = ips[ipKey][category];

  // If user has already voted for another entry, decrement its votes
  if (prevVotedId) {
    const prevItem = list.find(e => e.id === prevVotedId);
    if (prevItem && prevItem.votes > 0) prevItem.votes -= 1;
  }

  // Add new entry with 1 vote
  const entry = { id: Date.now().toString(), name, votes: 1 };
  list.push(entry);
  writeJson(DATA_FILE, data);

  // Update IP record to new entry id for this category
  ips[ipKey][category] = entry.id;
  writeJson(IP_FILE, ips);

  res.json(entry);
});

/*  Vote for existing entry  */
app.post('/api/vote', (req, res) => {
  const { id, category } = req.body;
  if (!validateCategory(category)) return res.status(400).json({ error: 'Invalid category' });

  const data = readJson(DATA_FILE, {});
  const list = data[category] = data[category] || [];
  const item = list.find(e => e.id === id);
  if (!item) return res.status(404).json({ error: 'Entry not found' });

  const ips = ensureValidIpTracking();
  const ipKey = hash(req.clientIp || 'unknown');
  if (!ips[ipKey] || typeof ips[ipKey] !== 'object') ips[ipKey] = {};
  const prevVotedId = ips[ipKey][category];

  if (prevVotedId === id) {
    // Already voted for this option
    return res.status(409).json({ error: 'You have already voted for this option' });
  }

  // If user has voted for a different option, decrement that vote
  if (prevVotedId) {
    const prevItem = list.find(e => e.id === prevVotedId);
    if (prevItem && prevItem.votes > 0) prevItem.votes -= 1;
  }

  // Increment vote for the new option
  item.votes += 1;
  writeJson(DATA_FILE, data);

  // Update IP record to new voted id for this category
  ips[ipKey][category] = id;
  writeJson(IP_FILE, ips);

  res.json(item);
});

/* ---------- Archive API ---------- */
// Get list of archived weeks
app.get('/api/archives/weeks', (req, res) => {
  try {
    const weeks = archiver.getArchivedWeeks();
    res.json(weeks);
  } catch (error) {
    console.error('Error getting archived weeks:', error);
    res.status(500).json({ error: 'Failed to retrieve archived weeks' });
  }
});

// Get archived data for a specific week
app.get('/api/archives/week/:weekId', (req, res) => {
  try {
    const { weekId } = req.params;
    const archive = archiver.getArchivedWeek(weekId);
    
    if (!archive) {
      return res.status(404).json({ error: 'Archive not found for the specified week' });
    }
    
    res.json(archive);
  } catch (error) {
    console.error('Error getting archived week:', error);
    res.status(500).json({ error: 'Failed to retrieve archived data' });
  }
});

// Get archived data for a specific week and category
app.get('/api/archives/week/:weekId/category/:category', (req, res) => {
  try {
    const { weekId, category } = req.params;
    const archive = archiver.getArchivedWeek(weekId);
    
    if (!archive) {
      return res.status(404).json({ error: 'Archive not found for the specified week' });
    }
    
    if (!validateCategory(category)) {
      return res.status(400).json({ error: 'Invalid category' });
    }
    
    const entries = (archive.data[category] || []).sort((a, b) => b.votes - a.votes);
    res.json(entries);
  } catch (error) {
    console.error('Error getting archived category:', error);
    res.status(500).json({ error: 'Failed to retrieve archived data' });
  }
});

// Get archived data for a date range
app.get('/api/archives/range', (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    
    if (!startDate || !endDate) {
      return res.status(400).json({ error: 'Both startDate and endDate are required' });
    }
    
    const archives = archiver.getArchivedRange(startDate, endDate);
    res.json(archives);
  } catch (error) {
    console.error('Error getting archived range:', error);
    res.status(500).json({ error: 'Failed to retrieve archived data for the specified range' });
  }
});

/* ---------- Hugging Face API Proxy ---------- */
app.get('/api/huggingface/models', (req, res) => {
  const query = req.query.query;
  
  if (!query || query.length < 2) {
    return res.status(400).json({ error: 'Query must be at least 2 characters' });
  }
  
  const options = {
    hostname: 'huggingface.co',
    path: `/api/models?search=${encodeURIComponent(query)}`,
    method: 'GET',
    headers: {
      'Accept': 'application/json'
    }
  };
  
  const hfRequest = https.request(options, (hfResponse) => {
    let data = '';
    
    hfResponse.on('data', (chunk) => {
      data += chunk;
    });
    
    hfResponse.on('end', () => {
      try {
        const parsedData = JSON.parse(data);
        
        // Format the response to include only necessary information
        const formattedResults = parsedData.map(model => ({
          id: model.id,
          modelId: model.modelId,
          name: model.name || model.id,
          author: model.author?.name || 'Unknown',
          downloads: model.downloads || 0,
          likes: model.likes || 0
        })).slice(0, 10); // Limit to 10 results
        
        res.json(formattedResults);
      } catch (error) {
        console.error('Error parsing Hugging Face API response:', error);
        res.status(500).json({ error: 'Failed to parse Hugging Face API response' });
      }
    });
  });
  
  hfRequest.on('error', (error) => {
    console.error('Error fetching from Hugging Face API:', error);
    res.status(500).json({ error: 'Failed to fetch from Hugging Face API' });
  });
  
  hfRequest.end();
});

/* ---------- start ---------- */
app.listen(PORT, () => console.log('Leaderboard running on', PORT));