rohanshaw commited on
Commit
9ed06fa
Β·
verified Β·
1 Parent(s): bce0681

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +23 -0
  2. index.js +109 -0
  3. models/Analytics.js +24 -0
  4. package.json +20 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use official Node.js image
2
+ FROM node:18
3
+
4
+ # Create app directory
5
+ WORKDIR /app
6
+
7
+ # Copy package files
8
+ COPY package*.json ./
9
+
10
+ # Install dependencies
11
+ RUN npm install
12
+
13
+ # Copy source code
14
+ COPY . .
15
+
16
+ # Expose the port Hugging Face expects (7860)
17
+ EXPOSE 7860
18
+
19
+ # Define environment variable for port
20
+ ENV PORT=7860
21
+
22
+ # Start the app
23
+ CMD [ "npm", "start" ]
index.js ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ require('dotenv').config();
2
+ const express = require('express');
3
+ const mongoose = require('mongoose');
4
+ const cors = require('cors');
5
+ const helmet = require('helmet');
6
+ const Analytics = require('./models/Analytics');
7
+
8
+ const app = express();
9
+ const PORT = process.env.PORT || 7860; // 7860 is the default for HuggingFace Spaces
10
+
11
+ // --- Middleware ---
12
+ app.use(helmet()); // Adds security headers
13
+ app.use(express.json()); // Parses JSON body
14
+ // In production, replace '*' with your frontend domain (e.g., 'https://comprex.pages.dev')
15
+ app.use(cors({ origin: '*' }));
16
+
17
+ // --- Database Connection ---
18
+ const connectDB = async () => {
19
+ try {
20
+ // We use the MONGO_URI from .env
21
+ await mongoose.connect(process.env.MONGO_URI);
22
+ console.log('βœ… MongoDB Connected Successfully');
23
+ } catch (err) {
24
+ console.error('❌ MongoDB Connection Error:', err);
25
+ process.exit(1); // Exit if DB fails
26
+ }
27
+ };
28
+ connectDB();
29
+
30
+ // --- Routes ---
31
+
32
+ // 1. Health Check
33
+ app.get('/', (req, res) => {
34
+ res.json({ status: 'active', message: 'CompreX Backend is running' });
35
+ });
36
+
37
+ // 2. Track Compression (Frontend calls this after compressing a file)
38
+ app.post('/api/track', async (req, res) => {
39
+ try {
40
+ const { fileType, originalSize, compressedSize } = req.body;
41
+
42
+ // Basic Validation
43
+ if (!fileType || !originalSize || !compressedSize) {
44
+ return res.status(400).json({ error: 'Missing required fields' });
45
+ }
46
+
47
+ const newStat = await Analytics.create({
48
+ fileType,
49
+ originalSize,
50
+ compressedSize
51
+ });
52
+
53
+ res.status(201).json({ success: true, id: newStat._id });
54
+ } catch (error) {
55
+ console.error('Tracking Error:', error);
56
+ res.status(500).json({ error: 'Server Error' });
57
+ }
58
+ });
59
+
60
+ // 3. Get Dashboard Stats (For the Analytics Page)
61
+ app.get('/api/stats', async (req, res) => {
62
+ try {
63
+ // Aggregation Pipeline for Performance
64
+ const stats = await Analytics.aggregate([
65
+ {
66
+ $group: {
67
+ _id: null,
68
+ totalFiles: { $sum: 1 },
69
+ totalOriginal: { $sum: "$originalSize" },
70
+ totalCompressed: { $sum: "$compressedSize" }
71
+ }
72
+ }
73
+ ]);
74
+
75
+ // Get Daily Activity for the last 7 days (For the Chart)
76
+ const sevenDaysAgo = new Date();
77
+ sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
78
+
79
+ const history = await Analytics.aggregate([
80
+ { $match: { timestamp: { $gte: sevenDaysAgo } } },
81
+ {
82
+ $group: {
83
+ _id: { $dateToString: { format: "%Y-%m-%d", date: "$timestamp" } },
84
+ count: { $sum: 1 },
85
+ savedBytes: { $sum: { $subtract: ["$originalSize", "$compressedSize"] } }
86
+ }
87
+ },
88
+ { $sort: { _id: 1 } } // Sort by date ascending
89
+ ]);
90
+
91
+ const globalStats = stats[0] || { totalFiles: 0, totalOriginal: 0, totalCompressed: 0 };
92
+ const totalSaved = globalStats.totalOriginal - globalStats.totalCompressed;
93
+
94
+ res.json({
95
+ totalFiles: globalStats.totalFiles,
96
+ totalSavedBytes: totalSaved,
97
+ history
98
+ });
99
+
100
+ } catch (error) {
101
+ console.error('Stats Error:', error);
102
+ res.status(500).json({ error: 'Server Error' });
103
+ }
104
+ });
105
+
106
+ // --- Start Server ---
107
+ app.listen(PORT, () => {
108
+ console.log(`πŸš€ Server running on port ${PORT}`);
109
+ });
models/Analytics.js ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const mongoose = require('mongoose');
2
+
3
+ const AnalyticsSchema = new mongoose.Schema({
4
+ fileType: {
5
+ type: String,
6
+ required: true,
7
+ enum: ['image', 'video', 'pdf', 'audio'], // Restrict to known types
8
+ },
9
+ originalSize: {
10
+ type: Number, // in bytes
11
+ required: true,
12
+ },
13
+ compressedSize: {
14
+ type: Number, // in bytes
15
+ required: true,
16
+ },
17
+ timestamp: {
18
+ type: Date,
19
+ default: Date.now,
20
+ index: true // Indexing makes dashboard queries faster
21
+ }
22
+ });
23
+
24
+ module.exports = mongoose.model('Analytics', AnalyticsSchema);
package.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "backend",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "scripts": {
6
+ "start": "node index.js",
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [],
10
+ "author": "",
11
+ "license": "ISC",
12
+ "description": "",
13
+ "dependencies": {
14
+ "cors": "^2.8.5",
15
+ "dotenv": "^17.2.3",
16
+ "express": "^5.1.0",
17
+ "helmet": "^8.1.0",
18
+ "mongoose": "^9.0.0"
19
+ }
20
+ }