-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
729 lines (655 loc) · 23 KB
/
Copy pathserver.js
File metadata and controls
729 lines (655 loc) · 23 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
import express from "express";
import bodyParser from "body-parser";
import googlePlay from "google-play-scraper";
import appStore from "app-store-scraper";
import fsPromises from "fs/promises";
import { Parser } from "json2csv";
import dotenv from "dotenv";
import { Storage } from "@google-cloud/storage";
import path from "path";
import { spawn } from "child_process";
import { count } from "console";
dotenv.config();
// Google Cloud Storage credentials
const credentials = {
type: process.env.TYPE,
project_id: process.env.PROJECT_ID,
private_key_id: process.env.PRIVATE_KEY_ID,
private_key: process.env.PRIVATE_KEY.split(String.raw`\n`).join("\n"),
client_email: process.env.CLIENT_EMAIL,
client_id: process.env.CLIENT_ID,
auth_uri: process.env.AUTH_URI,
token_uri: process.env.TOKEN_URI,
auth_provider_x509_cert_url: process.env.AUTH_PROVIDER_X509_CERT_URL,
client_x509_cert_url: process.env.CLIENT_X509_CERT_URL,
};
// Create an Express app
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Google Cloud Storage configuration
const storage = new Storage({
credentials,
});
const bucketName = process.env.GCS_BUCKET_NAME;
const folderPath = process.env.GCS_FOLDER_PATH;
// CSV parser configuration
const parser = new Parser({
delimiter: ",",
quote: '"',
escape: '"',
});
// Start the server
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
console.log('Python path:', process.env.PYTHON_PATH || "python3");
});
// Routes
app.get("/search", async (req, res) => {
const { term, country, num } = req.query;
if (!term || !country || !num) {
return res.status(400).send("Missing term or num parameter");
}
try {
const results = await searchFetchAppDetails(term, country, num);
res.json(results);
} catch (error) {
console.error(error);
res.status(500).send("Error fetching app details");
}
});
app.get("/collection", async (req, res) => {
const { collection, country, num } = req.query;
if (!collection || !country || !num) {
return res
.status(400)
.send("Missing collection, country, or num parameter");
}
try {
// Decide which function to call based on the platform parameter
const results = await collectionFetchAppDetails(collection, country, num);
res.json(results);
} catch (error) {
console.error(error);
res.status(500).send("Error fetching app details");
}
});
// Route to get similar apps based on an app name
app.get("/similar", async (req, res) => {
const { appName, country } = req.query;
if (!appName || !country) {
return res.status(400).send("Missing appName or country parameter");
}
try {
const results = await similarFetchAppDetails(appName, country);
res.json(results);
} catch (error) {
console.error("Failed to fetch similar apps:", error);
res.status(500).send("Error fetching similar apps");
}
});
// Function to fetch app details for a collection of apps
async function collectionFetchAppDetails(
collectionList,
countryList,
collectionNumResults
) {
const collectionIOS = collectionList + "_IOS";
try {
const collectionResultsAppStore = await appStore.list({
collection: appStore.collection.collectionIOS,
country: countryList,
num: collectionNumResults,
fullDetail: true,
});
const collectionResultsGooglePlay = await googlePlay.list({
collection: googlePlay.collection.collectionList,
country: countryList,
num: collectionNumResults,
fullDetail: true,
});
// Fetch reviews for each app in the App Store collection
const appStoreReviewsPromises = collectionResultsAppStore.map((app) =>
fetchAppStoreReviews(app.appId, countryList)
.then((reviews) => {
app.reviews = reviews; // Append reviews to the app object
return app;
})
.catch((error) => {
console.error(
`Failed to fetch App Store reviews for ${app.appId}: ${error}`
);
app.reviews = "Failed to fetch reviews";
return app;
})
);
// Fetch reviews for each app in the Google Play collection
const googlePlayReviewsPromises = collectionResultsGooglePlay.map((app) =>
fetchGooglePlayReviews(app.appId, countryList)
.then((reviews) => {
app.reviews = reviews; // Append reviews to the app object
return app;
})
.catch((error) => {
console.error(
`Failed to fetch Google Play reviews for ${app.appId}: ${error}`
);
app.reviews = "Failed to fetch reviews";
return app;
})
);
// Wait for all reviews to be fetched
const updatedCollectionResultsAppStore = await Promise.all(
appStoreReviewsPromises
);
const updatedCollectionResultsGooglePlay = await Promise.all(
googlePlayReviewsPromises
);
const csvAppStore = parser.parse(updatedCollectionResultsAppStore);
const csvGooglePlay = parser.parse(updatedCollectionResultsGooglePlay);
await fsPromises.writeFile("GooglePlayOutput.csv", csvGooglePlay);
console.log("Successfully wrote to CSV Google Play file");
await fsPromises.writeFile("AppStoreOutput.csv", csvAppStore);
console.log("Successfully wrote to CSV Appstore file");
executePythonScript(
"transform_GooglePlayData",
"./GooglePlayOutput.csv",
"./GooglePlayOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("GooglePlayOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"GooglePlayOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlayOutput_cleaned.csv:",
error
)
);
uploadFileToGCS("GooglePlay_Categories.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Categories successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Categories:", error)
);
uploadFileToGCS("GooglePlay_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Bigrams successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Bigrams.csv:", error)
);
uploadFileToGCS(
"GooglePlay_Word_Frequencies.csv",
bucketName,
folderPath
)
.then(() =>
console.log(
"GooglePlay_Word_Frequencies successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlay_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
executePythonScript(
"transform_AppStoreData",
"./AppStoreOutput.csv",
"./AppStoreOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("AppStoreOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStoreOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error("Failed to upload AppStoreOutput_cleaned.csv:", error)
);
uploadFileToGCS("AppStore_Genres.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Genres.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Genres.csv:", error)
);
uploadFileToGCS("AppStore_Languages.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Languages.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Languages.csv:", error)
);
uploadFileToGCS("AppStore_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Bigrams.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Bigrams.csv:", error)
);
uploadFileToGCS("AppStore_Word_Frequencies.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStore_Word_Frequencies.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload AppStore_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
return { collectionResultsAppStore, collectionResultsGooglePlay };
} catch (error) {
console.error("Failed to fetch app details:", error);
throw error;
}
}
async function searchFetchAppDetails(searchTerm, countryList, numResults) {
try {
const searchResultsGooglePlay = await googlePlay.search({
term: searchTerm,
country: countryList,
num: numResults,
});
const searchResultsAppStore = await appStore.search({
term: searchTerm,
country: countryList,
num: numResults,
});
// Fetch detailed app info and reviews for Google Play apps
const detailedAppsGooglePlay = await Promise.all(
searchResultsGooglePlay.map(async (app) => {
const details = await googlePlay.app({
appId: app.appId,
country: countryList,
});
const reviews = await fetchGooglePlayReviews(app.appId, countryList);
return { ...details, reviews }; // Include reviews in the app details
})
);
// Fetch detailed app info and reviews for App Store apps
const detailedAppsAppStore = await Promise.all(
searchResultsAppStore.map(async (app) => {
const details = await appStore.app({
appId: app.appId,
country: countryList,
});
const reviews = await fetchAppStoreReviews(app.appId, countryList);
return { ...details, reviews }; // Include reviews in the app details
})
);
const csvGooglePlay = parser.parse(detailedAppsGooglePlay);
const csvAppStore = parser.parse(detailedAppsAppStore);
await fsPromises.writeFile("AppStoreOutput.csv", csvAppStore);
console.log("Successfully wrote to CSV Appstore file");
await fsPromises.writeFile("GooglePlayOutput.csv", csvGooglePlay);
console.log("Successfully wrote to CSV Google Play file");
executePythonScript(
"transform_GooglePlayData",
"./GooglePlayOutput.csv",
"./GooglePlayOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("GooglePlayOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"GooglePlayOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlayOutput_cleaned.csv:",
error
)
);
uploadFileToGCS("GooglePlay_Categories.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Categories successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Categories:", error)
);
uploadFileToGCS("GooglePlay_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Bigrams successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Bigrams.csv:", error)
);
uploadFileToGCS(
"GooglePlay_Word_Frequencies.csv",
bucketName,
folderPath
)
.then(() =>
console.log(
"GooglePlay_Word_Frequencies successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlay_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
executePythonScript(
"transform_AppStoreData",
"./AppStoreOutput.csv",
"./AppStoreOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("AppStoreOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStoreOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error("Failed to upload AppStoreOutput_cleaned.csv:", error)
);
uploadFileToGCS("AppStore_Genres.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Genres.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Genres.csv:", error)
);
uploadFileToGCS("AppStore_Languages.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Languages.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Languages.csv:", error)
);
uploadFileToGCS("AppStore_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Bigrams.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Bigrams.csv:", error)
);
uploadFileToGCS("AppStore_Word_Frequencies.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStore_Word_Frequencies.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload AppStore_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
return { detailedAppsGooglePlay, detailedAppsAppStore };
} catch (error) {
console.error("Failed to fetch app details:", error);
throw error;
}
}
async function similarFetchAppDetails(appName, country) {
try {
// Initial search to find the app ID from the app name
const searchResultsGooglePlay = await googlePlay.search({
term: appName,
country: country,
num: 1,
});
const searchResultsAppStore = await appStore.search({
term: appName,
country: country,
num: 1,
});
// Extract app IDs (assuming the most relevant result is the first one)
const appIdGooglePlay = searchResultsGooglePlay[0]?.appId;
const appIdAppStore = searchResultsAppStore[0]?.appId;
// Fetch similar apps using the retrieved app IDs
const similarAppsGooglePlay = appIdGooglePlay
? await googlePlay.similar({
appId: appIdGooglePlay,
country: country,
fullDetail: true,
})
: [];
const similarAppsAppStore = appIdAppStore
? await appStore.similar({
appId: appIdAppStore,
country: country,
fullDetail: true,
})
: [];
// Fetch detailed app info and reviews for similar Google Play apps
const detailedGooglePlayApps = await Promise.all(
similarAppsGooglePlay.map(async (app) => {
const reviews = await fetchGooglePlayReviews(app.appId, country);
return { ...app, reviews }; // Include reviews in the app details
})
);
// Fetch detailed app info and reviews for similar App Store apps
const detailedAppStoreApps = await Promise.all(
similarAppsAppStore.map(async (app) => {
const reviews = await fetchAppStoreReviews(app.appId, country);
return { ...app, reviews }; // Include reviews in the app details
})
);
// Convert results to CSV
const csvGooglePlay = parser.parse(detailedGooglePlayApps);
const csvAppStore = parser.parse(detailedAppStoreApps);
await fsPromises.writeFile("AppStoreOutput.csv", csvAppStore);
console.log("Successfully wrote to CSV Appstore file");
await fsPromises.writeFile("GooglePlayOutput.csv", csvGooglePlay);
console.log("Successfully wrote to CSV Google Play file");
executePythonScript(
"transform_GooglePlayData",
"./GooglePlayOutput.csv",
"./GooglePlayOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("GooglePlayOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"GooglePlayOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlayOutput_cleaned.csv:",
error
)
);
uploadFileToGCS("GooglePlay_Categories.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Categories successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Categories:", error)
);
uploadFileToGCS("GooglePlay_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("GooglePlay_Bigrams successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload GooglePlay_Bigrams.csv:", error)
);
uploadFileToGCS(
"GooglePlay_Word_Frequencies.csv",
bucketName,
folderPath
)
.then(() =>
console.log(
"GooglePlay_Word_Frequencies successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload GooglePlay_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
executePythonScript(
"transform_AppStoreData",
"./AppStoreOutput.csv",
"./AppStoreOutput_cleaned.csv"
)
.then(() => {
// Upload file to GCS after Python script completes
console.log("Now uploading to GCS...");
uploadFileToGCS("AppStoreOutput_cleaned.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStoreOutput_cleaned.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error("Failed to upload AppStoreOutput_cleaned.csv:", error)
);
uploadFileToGCS("AppStore_Genres.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Genres.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Genres.csv:", error)
);
uploadFileToGCS("AppStore_Languages.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Languages.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Languages.csv:", error)
);
uploadFileToGCS("AppStore_Bigrams.csv", bucketName, folderPath)
.then(() =>
console.log("AppStore_Bigrams.csv successfully uploaded to GCS")
)
.catch((error) =>
console.error("Failed to upload AppStore_Bigrams.csv:", error)
);
uploadFileToGCS("AppStore_Word_Frequencies.csv", bucketName, folderPath)
.then(() =>
console.log(
"AppStore_Word_Frequencies.csv successfully uploaded to GCS"
)
)
.catch((error) =>
console.error(
"Failed to upload AppStore_Word_Frequencies.csv:",
error
)
);
})
.catch((error) => {
console.error("Failed to execute Python script:", error);
});
return { detailedGooglePlayApps, detailedAppStoreApps };
} catch (error) {
console.error("Failed to fetch app details:", error);
throw error;
}
}
// Function to fetch Google Play app reviews
async function fetchGooglePlayReviews(appId, countryList, numOfReviews = 200) {
const reviews = await googlePlay.reviews({
appId: appId,
num: numOfReviews,
country: countryList,
});
// Concatenate review texts into a single string
return reviews.data.map((review) => review.text).join(" | ");
}
// Function to fetch App Store reviews
async function fetchAppStoreReviews(appId, countryList, numOfReviews = 200) {
const reviews = await appStore.reviews({
appId: appId,
num: numOfReviews,
country: countryList,
});
// Concatenate review texts into a single string
return reviews.map((review) => review.text).join(" | ");
}
// Function to upload files to GCS
async function uploadFileToGCS(fileName, bucketName, folderPath) {
try {
// Construct the full path within the bucket
const destinationPath = path.join(folderPath, fileName);
await storage.bucket(bucketName).upload(fileName, {
destination: destinationPath,
});
console.log(
`${fileName} uploaded to ${bucketName} in folder ${folderPath}`
);
} catch (error) {
console.error(
`Failed to upload ${fileName} to Google Cloud Storage in folder ${folderPath}`,
error
);
}
}
// Function that returns a promise which resolves when the Python script is done
function executePythonScript(functionName, inputFilePath, outputFilePath) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn(process.env.PYTHON_PATH || "python3", [
"transform.py",
functionName,
inputFilePath,
outputFilePath,
]);
pythonProcess.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
console.log(process.env.PYTHON_PATH);
});
pythonProcess.stderr.on("data", (data) => {
console.error(`stderr: ${data.toString()}`);
console.log(process.env.PYTHON_PATH);
});
pythonProcess.on("close", (code) => {
if (code === 0) {
console.log("Python script completed successfully");
resolve(); // Resolve the promise upon successful completion
} else {
console.error("Python script failed with code " + code);
reject(new Error("Python script failed with code " + code)); // Reject the promise on failure
}
});
});
}