-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
3473 lines (3010 loc) · 105 KB
/
Copy pathserver.js
File metadata and controls
3473 lines (3010 loc) · 105 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("dotenv").config();
// ========== DUAL-CLOUD TOGGLE ==========
const USE_GOOGLE_CLOUD = process.env.USE_GOOGLE_CLOUD === "true";
console.log(
`\n🌐 Cloud Provider: ${USE_GOOGLE_CLOUD ? "Google Cloud" : "Azure"}\n`,
);
// Google Cloud SDKs (conditionally loaded)
let firebaseAdmin, firestoreDb, gcsBucket;
if (USE_GOOGLE_CLOUD) {
try {
firebaseAdmin = require("firebase-admin");
const { Storage } = require("@google-cloud/storage");
// Try to load service account from JSON file first, fallback to env vars
let serviceAccountCredentials;
const fs = require("fs");
if (fs.existsSync("./service-account-key.json")) {
// Use JSON file (local development)
serviceAccountCredentials = require("./service-account-key.json");
} else if (
process.env.GOOGLE_PROJECT_ID &&
process.env.GOOGLE_CLIENT_EMAIL &&
process.env.GOOGLE_PRIVATE_KEY
) {
// Use environment variables (production deployment)
serviceAccountCredentials = {
type: "service_account",
project_id: process.env.GOOGLE_PROJECT_ID,
private_key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n"),
client_email: process.env.GOOGLE_CLIENT_EMAIL,
};
console.log("📋 Using service account from environment variables");
} else {
throw new Error(
"No service account credentials found (JSON file or env vars)",
);
}
// Initialize Firebase Admin with service account
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccountCredentials),
});
firestoreDb = firebaseAdmin.firestore();
console.log("✅ Firebase/Firestore initialized.");
// Initialize GCS
const gcsStorage = new Storage({
projectId: serviceAccountCredentials.project_id,
credentials: serviceAccountCredentials,
});
gcsBucket = gcsStorage.bucket(process.env.GCS_BUCKET_NAME);
console.log(
`✅ Google Cloud Storage initialized (Bucket: ${process.env.GCS_BUCKET_NAME})`,
);
console.log("ℹ️ AI Analysis: Using Azure Vision + Azure Gemini");
} catch (gcpError) {
console.error("❌ Google Cloud initialization failed:", gcpError.message);
console.log(
" Make sure service-account-key.json exists OR GOOGLE_PROJECT_ID, GOOGLE_CLIENT_EMAIL, GOOGLE_PRIVATE_KEY are set in .env",
);
}
}
const express = require("express");
const path = require("path");
const { CosmosClient } = require("@azure/cosmos");
const crypto = require("crypto");
const nodemailer = require("nodemailer");
const Razorpay = require("razorpay");
const session = require("express-session");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const GitHubStrategy = require("passport-github2").Strategy;
// Azure AI SDKs for file processing
const createImageAnalysisClient =
require("@azure-rest/ai-vision-image-analysis").default;
const { AzureKeyCredential } = require("@azure/core-auth");
// Document parsing libraries
const pdfParse = require("pdf-parse");
const mammoth = require("mammoth");
const XLSX = require("xlsx");
const app = express();
const PORT = process.env.PORT || 3000;
// ========== AZURE AI CLIENT INITIALIZATION ==========
// Azure OpenAI Client (GPT-4o for content quality analysis)
let openaiClient = null;
const OPENAI_DEPLOYMENT = "gpt-4o";
function getOpenAIClient() {
if (
!openaiClient &&
process.env.AZURE_OPENAI_ENDPOINT &&
process.env.AZURE_OPENAI_KEY
) {
// Use the official 'openai' package which provides AzureOpenAI class
const { AzureOpenAI } = require("openai");
openaiClient = new AzureOpenAI({
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiKey: process.env.AZURE_OPENAI_KEY,
apiVersion: "2024-02-15-preview",
deployment: OPENAI_DEPLOYMENT,
});
console.log("Azure Gemini client initialized.");
}
return openaiClient;
}
// Azure Vision Client (Image tagging and captioning)
let visionClient = null;
function getVisionClient() {
if (!visionClient && process.env.VISION_ENDPOINT && process.env.VISION_KEY) {
visionClient = createImageAnalysisClient(
process.env.VISION_ENDPOINT,
new AzureKeyCredential(process.env.VISION_KEY),
);
console.log("Azure Vision AI client initialized.");
}
return visionClient;
}
// Azure Document Intelligence Client (Using native fetch for zero-dependency)
async function analyzeWithDI(fileBuffer) {
const endpoint = process.env.AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT;
const key = process.env.AZURE_DOCUMENT_INTELLIGENCE_KEY;
if (!endpoint || !key) {
console.warn("Document Intelligence not configured");
return { text: "" };
}
try {
// 1. Start Analysis
const response = await fetch(
`${endpoint}/documentintelligence/documentModels/prebuilt-read:analyze?api-version=2024-11-30`,
{
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": key,
"Content-Type": "application/octet-stream",
},
body: fileBuffer,
},
);
if (!response.ok) {
const errText = await response.text();
throw new Error(
`DI Analysis startup failed: ${response.status} ${errText}`,
);
}
// 2. Get Operation Location for Polling
const operationUrl = response.headers.get("Operation-Location");
if (!operationUrl) throw new Error("No Operation-Location header found");
// 3. Poll for results
let result = null;
let attempts = 0;
const maxAttempts = 30;
while (attempts < maxAttempts) {
const pollResponse = await fetch(operationUrl, {
headers: { "Ocp-Apim-Subscription-Key": key },
});
result = await pollResponse.json();
if (result.status === "succeeded") break;
if (result.status === "failed") throw new Error("DI Analysis failed");
attempts++;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
if (!result || result.status !== "succeeded") {
throw new Error("DI Analysis timed out or failed");
}
return {
text: result.analyzeResult?.content || "",
modelId: "prebuilt-read",
};
} catch (e) {
console.error("Document Intelligence analysis failed:", e.message);
return { text: "", error: e.message };
}
}
// Content Safety Check (simplified - logs warning if not configured)
async function analyzeContentSafety(content, isImage = false) {
// Content Safety SDK requires separate installation
// For now, return safe by default with warning
console.log("Content Safety check skipped (SDK not configured)");
return { isSafe: true, reason: "Content Safety not configured" };
}
// GPT-4o Content Quality Analysis
async function analyzeContentQualityGPT4o(content, filename, diText = "") {
try {
const client = getOpenAIClient();
if (!client) {
console.warn("OpenAI not configured - using default score");
return {
quality_score: 50,
payout: 10,
ai_analysis: { error: "OpenAI not configured" },
};
}
// Combine preview content and extracted DI text
const preview = content.substring(0, 4000);
const textPart = diText
? `\nExtracted Text from Document Intelligence:\n${diText.substring(0, 4000)}`
: "";
const prompt = `Analyze the following file named '${filename}'. ${textPart}
Determine:
1. Is this valid, high-quality code/text/document?
2. What does it do? (Short summary)
3. Assign a 'Trust Score' from 1 to 100 based on utility, cleanliness, and complexity.
Return ONLY a JSON object:
{
"trust_score": <int>,
"summary": "<string>",
"reasoning": "<string>"
}
Content Preview:
${preview}`;
const response = await client.chat.completions.create({
model: OPENAI_DEPLOYMENT,
messages: [
{
role: "system",
content: "You are a senior code auditor and data quality expert.",
},
{ role: "user", content: prompt },
],
response_format: { type: "json_object" },
});
const resultJson = JSON.parse(response.choices[0].message.content);
const score = resultJson.trust_score || 50;
return {
quality_score: score,
payout: calculatePayout(score),
ai_analysis: {
summary: resultJson.summary,
reasoning: resultJson.reasoning,
},
};
} catch (e) {
console.error("OpenAI analysis failed:", e.message);
return { quality_score: 50, payout: 10, ai_analysis: { error: e.message } };
}
}
// Azure Vision 4.0 Image Analysis
async function analyzeImageVision(imageBuffer) {
try {
const client = getVisionClient();
if (!client) {
console.warn("Vision AI not configured - using default analysis");
return {
tags: [],
caption: "Vision AI not configured",
ai_analysis: { error: "Not configured" },
};
}
const response = await client.path("/imageanalysis:analyze").post({
body: imageBuffer,
queryParameters: {
features: ["tags", "caption"],
},
contentType: "application/octet-stream",
});
if (response.status !== "200") {
throw new Error(`Vision API error: ${response.status}`);
}
const result = response.body;
const tags = result.tagsResult?.values?.map((t) => t.name) || [];
const caption = result.captionResult?.text || "No caption generated";
return {
tags: tags,
caption: caption,
ai_analysis: {
vision_model: "4.0",
confidence: result.captionResult?.confidence || 0,
},
};
} catch (e) {
console.error("Vision analysis failed:", e.message);
return {
tags: [],
caption: "Error in vision analysis",
ai_analysis: { error: e.message },
};
}
}
// Classify content into market category using GPT-4o
async function classifyContent(description) {
try {
const client = getOpenAIClient();
if (!client) return "General";
const response = await client.chat.completions.create({
model: OPENAI_DEPLOYMENT,
messages: [
{
role: "system",
content:
"Classify this content into exactly ONE of these categories: 'Autonomous Driving', 'Medical Imaging', 'Robotics Training', 'Developer Tools', 'Financial Data', 'General'. Return only the category name.",
},
{ role: "user", content: description },
],
});
return response.choices[0].message.content.trim();
} catch (e) {
console.error("Classification failed:", e.message);
return "General";
}
}
// Calculate payout based on quality score (what user receives - 80% of price)
function calculatePayout(qualityScore) {
if (qualityScore < 50) {
return Math.max(0.1, qualityScore * 0.1);
} else if (qualityScore < 80) {
return 5 + (qualityScore - 50) * 0.5;
} else {
return 20 + (qualityScore - 80) * 4.0;
}
}
// Calculate price based on quality score (what agency pays)
// Price = Payout / 0.8 (since user gets 80%, platform takes 20%)
// Range: ~₹5 (low quality) to ~₹100+ (high quality)
function calculatePrice(qualityScore) {
const payout = calculatePayout(qualityScore);
return Math.round((payout / 0.8) * 100) / 100; // Round to 2 decimal places
}
// Middleware
app.use(express.json());
// Serve static files
app.use("/Agency", express.static(path.join(__dirname, "Agency")));
app.use("/User", express.static(path.join(__dirname, "User")));
app.use(express.static(__dirname));
// Clean URL routes for legal pages
app.get("/terms", (req, res) =>
res.sendFile(path.join(__dirname, "terms.html")),
);
app.get("/privacy", (req, res) =>
res.sendFile(path.join(__dirname, "privacy.html")),
);
app.get("/refund", (req, res) =>
res.sendFile(path.join(__dirname, "refund.html")),
);
// ========== SESSION & PASSPORT CONFIGURATION ==========
app.use(
session({
secret:
process.env.SESSION_SECRET || "mdata-oauth-secret-key-change-in-prod",
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === "production",
maxAge: 24 * 60 * 60 * 1000, // 24 hours
},
}),
);
app.use(passport.initialize());
app.use(passport.session());
// Passport serialize/deserialize
passport.serializeUser((user, done) => {
done(null, { id: user.id, role: user.role });
});
passport.deserializeUser(async (data, done) => {
try {
const container =
data.role === "agency" ? agenciesContainer : usersContainer;
if (!container) return done(null, false);
const { resource } = await container.item(data.id, data.id).read();
done(null, resource);
} catch (err) {
done(err, null);
}
});
// Google OAuth Strategy
if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL:
(process.env.BASE_URL || "http://localhost:3000") +
"/auth/google/callback",
passReqToCallback: true,
},
async (req, accessToken, refreshToken, profile, done) => {
try {
const email = profile.emails[0].value;
const role = req.session.oauthRole || "user";
const container =
role === "agency" ? agenciesContainer : usersContainer;
// Check if user exists
const { resources } = await container.items
.query({
query: "SELECT * FROM c WHERE c.email = @email",
parameters: [{ name: "@email", value: email }],
})
.fetchAll();
if (resources.length > 0) {
// User exists, log them in
return done(null, { ...resources[0], role });
}
// Create new user
const newUser = {
id: crypto.randomUUID(),
name: profile.displayName,
email: email,
oauth_provider: "google",
oauth_id: profile.id,
role: role === "agency" ? "agency" : "contributor",
balance: 0.0,
joined_date: new Date().toISOString(),
};
await container.items.create(newUser);
console.log(
`OAuth: Created new ${role} account for ${email} via Google`,
);
return done(null, { ...newUser, role });
} catch (err) {
console.error("Google OAuth error:", err);
return done(err, null);
}
},
),
);
console.log("Google OAuth strategy configured.");
}
// GitHub OAuth Strategy
if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {
passport.use(
new GitHubStrategy(
{
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL:
(process.env.BASE_URL || "http://localhost:3000") +
"/auth/github/callback",
scope: ["user:email"],
passReqToCallback: true,
},
async (req, accessToken, refreshToken, profile, done) => {
try {
const email =
profile.emails && profile.emails[0]
? profile.emails[0].value
: `${profile.username}@github.local`;
const role = req.session.oauthRole || "user";
const container =
role === "agency" ? agenciesContainer : usersContainer;
// Check if user exists
const { resources } = await container.items
.query({
query: "SELECT * FROM c WHERE c.email = @email",
parameters: [{ name: "@email", value: email }],
})
.fetchAll();
if (resources.length > 0) {
return done(null, { ...resources[0], role });
}
// Create new user
const newUser = {
id: crypto.randomUUID(),
name: profile.displayName || profile.username,
email: email,
oauth_provider: "github",
oauth_id: profile.id,
role: role === "agency" ? "agency" : "contributor",
balance: 0.0,
joined_date: new Date().toISOString(),
};
await container.items.create(newUser);
console.log(
`OAuth: Created new ${role} account for ${email} via GitHub`,
);
return done(null, { ...newUser, role });
} catch (err) {
console.error("GitHub OAuth error:", err);
return done(err, null);
}
},
),
);
console.log("GitHub OAuth strategy configured.");
}
// Azure Cosmos DB Configuration
const endpoint = process.env.COSMOS_ENDPOINT;
const key = process.env.COSMOS_KEY;
const databaseId = "mdatadb";
let database;
let usersContainer; // For contributor accounts
let agenciesContainer; // For agency/buyer accounts
async function initCosmos() {
try {
const client = new CosmosClient({ endpoint, key });
// Get or create database
const { database: db } = await client.databases.createIfNotExists({
id: databaseId,
});
database = db;
// Get or create Users container (for contributors)
const { container: usersC } = await database.containers.createIfNotExists({
id: "Users",
partitionKey: { paths: ["/id"] },
});
usersContainer = usersC;
console.log(`Connected to Azure Cosmos DB: ${databaseId} > Users`);
// Get or create Agencies container (for buyers)
const { container: agenciesC } =
await database.containers.createIfNotExists({
id: "Agencies",
partitionKey: { paths: ["/id"] },
});
agenciesContainer = agenciesC;
console.log(`Connected to Azure Cosmos DB: ${databaseId} > Agencies`);
} catch (err) {
console.error("Failed to connect to Cosmos DB:", err.message);
}
}
initCosmos();
// Azure Storage Configuration
const {
BlobServiceClient,
StorageSharedKeyCredential,
generateBlobSASQueryParameters,
ContainerSASPermissions,
} = require("@azure/storage-blob");
const storageConnectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;
let blobServiceClient;
let containerClient;
try {
if (storageConnectionString) {
blobServiceClient = BlobServiceClient.fromConnectionString(
storageConnectionString,
);
containerClient = blobServiceClient.getContainerClient("uploads");
console.log("Connected to Azure Blob Storage.");
} else {
console.warn("AZURE_STORAGE_CONNECTION_STRING not found in .env");
}
} catch (error) {
console.error("Error connecting to Azure Blob Storage:", error.message);
}
// Helper: SHA256 Hash
function hashPassword(password, salt) {
const hash = crypto.createHash("sha256");
hash.update(password + salt);
return hash.digest("hex");
}
// Routes
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
// ========== OAUTH ROUTES ==========
// Google OAuth - User
app.get("/auth/google", (req, res, next) => {
req.session.oauthRole = req.query.role || "user";
passport.authenticate("google", { scope: ["profile", "email"] })(
req,
res,
next,
);
});
app.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/?error=oauth_failed" }),
(req, res) => {
const role = req.user.role || "user";
const redirectUrl =
role === "agency" ? "/Agency/dashboard.html" : "/User/dashboard.html";
// Set localStorage via client-side script
const userData = JSON.stringify({
id: req.user.id,
name: req.user.name,
email: req.user.email,
role: role,
});
res.send(`
<script>
localStorage.setItem('user', '${userData.replace(/'/g, "\\'")}');
window.location.href = '${redirectUrl}';
</script>
`);
},
);
// GitHub OAuth
app.get("/auth/github", (req, res, next) => {
req.session.oauthRole = req.query.role || "user";
passport.authenticate("github", { scope: ["user:email"] })(req, res, next);
});
app.get(
"/auth/github/callback",
passport.authenticate("github", { failureRedirect: "/?error=oauth_failed" }),
(req, res) => {
const role = req.user.role || "user";
const redirectUrl =
role === "agency" ? "/Agency/dashboard.html" : "/User/dashboard.html";
const userData = JSON.stringify({
id: req.user.id,
name: req.user.name,
email: req.user.email,
role: role,
});
res.send(`
<script>
localStorage.setItem('user', '${userData.replace(/'/g, "\\'")}');
window.location.href = '${redirectUrl}';
</script>
`);
},
);
// API: User Stats
app.get("/api/stats", async (req, res) => {
const userId = req.query.userId;
if (!userId) {
return res.status(400).json({ error: "Missing userId" });
}
try {
let items = [];
if (USE_GOOGLE_CLOUD) {
// ========== FIRESTORE QUERY ==========
const snapshot = await firestoreDb
.collection("Submissions")
.where("userId", "==", userId)
.orderBy("upload_timestamp", "desc")
.get();
items = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
} else {
// ========== COSMOS DB QUERY ==========
const submissionsContainer = database.container("Submissions");
const querySpec = {
query:
"SELECT c.id, c.payout, c.quality_score, c.original_name, c.upload_timestamp, c.sold_to, c.transaction_date FROM c WHERE c.userId = @userId ORDER BY c.upload_timestamp DESC",
parameters: [{ name: "@userId", value: userId }],
};
const { resources } = await submissionsContainer.items
.query(querySpec)
.fetchAll();
items = resources;
}
let totalEarnings = 0.0;
let totalScore = 0;
const history = [];
// Initialize map for last 30 days revenue
const dailyMap = {};
const today = new Date();
for (let i = 0; i < 30; i++) {
const d = new Date();
d.setDate(today.getDate() - i);
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
dailyMap[`${yyyy}-${mm}-${dd}`] = 0;
}
items.forEach((item) => {
const payout = item.payout || 0;
const score = item.quality_score || 0;
const isSold = !!item.sold_to;
const userShare = isSold ? payout * 0.8 : 0;
if (isSold) {
totalEarnings += userShare;
if (item.transaction_date) {
const tDate = item.transaction_date.split("T")[0];
if (dailyMap.hasOwnProperty(tDate)) {
dailyMap[tDate] += userShare;
}
}
}
totalScore += score;
history.push({
id: item.id,
name: item.original_name || "Unknown",
date: item.upload_timestamp
? item.upload_timestamp.split("T")[0]
: "N/A",
upload_date: item.upload_timestamp
? new Date(item.upload_timestamp).toLocaleDateString()
: "N/A",
quality_score: score,
earnings: isSold ? `₹${userShare.toFixed(2)}` : "₹0.00",
status: isSold ? "Sold" : item.status || "Pending",
sold_to: item.sold_to || null,
sold_price: item.sold_price || 0,
});
});
const avgQuality =
items.length > 0 ? (totalScore / items.length).toFixed(1) : 0;
const sortedDates = Object.keys(dailyMap).sort();
const chartData = sortedDates.map((date) => ({
date,
amount: parseFloat(dailyMap[date].toFixed(2)),
}));
res.json({
earnings: `₹${totalEarnings.toFixed(2)}`,
quality: `${avgQuality}%`,
total_uploads: items.length,
history: history,
revenue_analytics: chartData,
});
} catch (error) {
console.error("Stats Error:", error);
res.json({
earnings: "₹0.00",
quality: "0%",
total_uploads: 0,
history: [],
revenue_analytics: [],
});
}
});
// API: File History
app.get("/api/files", async (req, res) => {
const userId = req.query.userId;
if (!userId) return res.status(400).json({ error: "Missing userId" });
try {
let items = [];
if (USE_GOOGLE_CLOUD) {
// ========== FIRESTORE QUERY ==========
const snapshot = await firestoreDb
.collection("Submissions")
.where("userId", "==", userId)
.orderBy("upload_timestamp", "desc")
.get();
items = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
} else {
// ========== COSMOS DB QUERY ==========
const submissionsContainer = database.container("Submissions");
const querySpec = {
query:
"SELECT * FROM c WHERE c.userId = @userId ORDER BY c.upload_timestamp DESC",
parameters: [{ name: "@userId", value: userId }],
};
const { resources } = await submissionsContainer.items
.query(querySpec)
.fetchAll();
items = resources;
}
res.json(items);
} catch (err) {
console.error("Files Error:", err);
res.status(500).json({ error: err.message });
}
});
// API: Delete File
app.delete("/api/files/:fileId", async (req, res) => {
const fileId = req.params.fileId;
const userId = req.query.userId;
if (!fileId || !userId) {
return res.status(400).json({ error: "Missing fileId or userId" });
}
try {
let item = null;
if (USE_GOOGLE_CLOUD) {
// ========== FIRESTORE QUERY & DELETE ==========
const docRef = firestoreDb.collection("Submissions").doc(fileId);
const doc = await docRef.get();
if (!doc.exists) {
return res.status(404).json({
error: "File not found or you don't have permission to delete it",
});
}
item = doc.data();
if (item.userId !== userId) {
return res.status(403).json({ error: "Permission denied" });
}
if (item.sold_to) {
return res
.status(400)
.json({ error: "Cannot delete a file that has already been sold" });
}
// Delete from Firestore
await docRef.delete();
console.log(`Deleted from Firestore: ${fileId}`);
// Delete from GCS
if (gcsBucket) {
try {
const file = gcsBucket.file(fileId);
await file.delete();
console.log(`Deleted from GCS: ${fileId}`);
} catch (gcsErr) {
console.warn("Failed to delete from GCS:", gcsErr.message);
}
}
} else {
// ========== COSMOS DB QUERY & DELETE ==========
const submissionsContainer = database.container("Submissions");
const querySpec = {
query: "SELECT * FROM c WHERE c.id = @fileId AND c.userId = @userId",
parameters: [
{ name: "@fileId", value: fileId },
{ name: "@userId", value: userId },
],
};
const { resources: items } = await submissionsContainer.items
.query(querySpec)
.fetchAll();
if (!items || items.length === 0) {
return res.status(404).json({
error: "File not found or you don't have permission to delete it",
});
}
item = items[0];
if (item.sold_to) {
return res
.status(400)
.json({ error: "Cannot delete a file that has already been sold" });
}
// Delete from Cosmos DB
await submissionsContainer.item(fileId, userId).delete();
// Delete from Azure Blob Storage
if (blobServiceClient && item.blob_url) {
try {
const blobName = item.blob_url.split("/").pop().split("?")[0];
const blobClient = containerClient.getBlobClient(blobName);
await blobClient.deleteIfExists();
console.log(`Deleted blob: ${blobName}`);
} catch (blobErr) {
console.warn("Failed to delete blob:", blobErr.message);
}
}
}
res.json({ message: "File deleted successfully", fileId });
} catch (err) {
console.error("Delete File Error:", err);
res.status(500).json({ error: err.message || "Failed to delete file" });
}
});
// API: Market Summaries
app.get("/api/market/summaries", async (req, res) => {
try {
let items = [];
if (USE_GOOGLE_CLOUD) {
// ========== FIRESTORE QUERY ==========
const snapshot = await firestoreDb.collection("Submissions").get();
items = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
} else {
// ========== COSMOS DB QUERY ==========
const container = database.container("Submissions");
const querySpec = {
query: "SELECT c.market_category, c.quality_score, c.sold_to FROM c",
};
const { resources } = await container.items.query(querySpec).fetchAll();
items = resources;
}
const marketStats = {};
items.forEach((item) => {
if (item.sold_to) return; // Skip sold items
const cat = item.market_category || "General";
const score = item.quality_score || 0;
if (!marketStats[cat]) {
marketStats[cat] = { count: 0, sum_score: 0 };
}
marketStats[cat].count++;
marketStats[cat].sum_score += score;
});
const result = Object.keys(marketStats).map((cat) => {
const avgQuality = marketStats[cat].sum_score / marketStats[cat].count;
const avgPrice = calculatePrice(avgQuality);
return {
market_category: cat,
total_files: marketStats[cat].count,
avg_quality: avgQuality.toFixed(1),
avg_price: avgPrice.toFixed(2),
};
});
res.json(result);
} catch (err) {
console.error("Market Summaries Error:", err);
res.status(500).json({ error: err.message });
}
});
// API: Market Category Preview (for agencies to see sample data before buying)
app.get("/api/market/preview/:category", async (req, res) => {
try {
const category = req.params.category;
if (!category) {
return res.status(400).json({ error: "Missing category parameter" });
}
let items = [];
if (USE_GOOGLE_CLOUD) {
const snapshot = await firestoreDb
.collection("Submissions")
.where("market_category", "==", category)
.where("sold_to", "==", null)