-
Notifications
You must be signed in to change notification settings - Fork 51
/
cron.js
180 lines (150 loc) · 5.41 KB
/
cron.js
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
import mongoose from 'mongoose';
import { configDotenv } from 'dotenv';
import User from './models/User.js';
var app = express();
import cors from 'cors';
app.use(cors());
import lookup from "coordinate_to_country"
import express from 'express';
import countries from './public/countries.json' with { type: "json" };
import findLatLongRandom from './components/findLatLongServer.js';
import cityGen from './serverUtils/cityGen.js';
import mainWorld from './public/world-main.json' with { type: "json" };
configDotenv();
// let dbEnabled = false;
// if (!process.env.MONGODB) {
// console.log("[MISSING-ENV WARN] MONGODB env variable not set".yellow);
// dbEnabled = false;
// } else {
// // Connect to MongoDB
// if (mongoose.connection.readyState !== 1) {
// try {
// await mongoose.connect(process.env.MONGODB);
// console.log('[INFO] Database Connected');
// dbEnabled = true;
// } catch (error) {
// console.error('[ERROR] Database connection failed!'.red, error.message);
// console.log(error);
// dbEnabled = false;
// }
// }
// }
let countryLocations = {};
const locationCnt = 2000;
const batchSize = 10;
for (const country of countries) {
countryLocations[country] = [];
}
const generateBalancedLocations = async () => {
while (true) {
const batchPromises = [];
// Loop through each country and start generating one batch for each
for (const country of countries) {
for (let i = 0; i < batchSize; i++) {
const startTime = Date.now(); // Start time for each country
const locationPromise = new Promise((resolve, reject) => {
findLatLongRandom({ location: country }, cityGen, lookup)
.then((latLong) => {
const endTime = Date.now(); // End time after fetching location
const duration = endTime - startTime; // Duration calculation
resolve({ country: latLong.country, latLong });
})
.catch(reject);
});
batchPromises.push(locationPromise);
}
}
try {
// Await the results of generating locations for all countries in parallel
const batchResults = await Promise.all(batchPromises);
for (const { country, latLong } of batchResults) {
// Update country-specific locations, ensuring a max of locationCnt
try {
if(countryLocations[country]) {
countryLocations[country].unshift(latLong);
if (countryLocations[country].length > locationCnt) {
countryLocations[country].pop();
}
}
} catch (error) {
console.error('Error updating country locations', error, country, latLong);
}
}
} catch (error) {
console.error('Error generating locations', error);
}
// Delay before starting the next round of generation
await new Promise((resolve) => setTimeout(resolve, 1000));
}
};
// Start generating balanced locations for all countries
generateBalancedLocations();
let allCountriesCache = [];
let lastAllCountriesCacheUpdate = 0;
app.get('/allCountries.json', (req, res) => {
if(Date.now() - lastAllCountriesCacheUpdate > 60 * 1000) {
// old world
// let locations = [];
// const totalCountries = countries.length;
// const locsPerCountry = locationCnt / totalCountries;
// for (const country of countries) {
// const locs = countryLocations[country];
// const randomLocations = locs.sort(() => Math.random() - 0.5).slice(0, locsPerCountry);
// locations.push(...randomLocations);
// }
// locations = locations.sort(() => Math.random() - 0.5);
// allCountriesCache = locations;
// lastAllCountriesCacheUpdate = Date.now();
// return res.json({ ready: locations.length>0, locations });
// new world
// pick 2k locations randomly from mainWorld, calculate country based on lat/long
// prevent duplicates
const totalLocs = mainWorld.length;
const neededLocs = 2000;
const indexes = new Set();
while (indexes.size < neededLocs) {
indexes.add(Math.floor(Math.random() * totalLocs));
}
const locations = [];
for (const index of indexes) {
try {
const { lat, lng } = mainWorld[index];
const country = lookup(lat, lng, true)[0];
locations.push({ lat, long: lng, country });
} catch (error) {
locations.push({ lat, long: lng });
console.error('Error looking up country', error, index);
}
}
allCountriesCache = locations;
lastAllCountriesCacheUpdate = Date.now();
return res.json({ ready: locations.length>0, locations });
} else {
return res.json({ ready: allCountriesCache.length>0, locations: allCountriesCache });
}
});
app.get('/countryLocations/:country', (req, res) => {
const country = req.params.country;
if (!countryLocations[country]) {
return res.status(404).json({ message: 'Country not found' });
}
return res.json({ ready:
countryLocations[country].length > 0,
locations: countryLocations[country] });
});
// Endpoint for /clueCountries.json
app.get('/clueCountries.json', (req, res) => {
if (clueLocations.length === 0) {
// send json {ready: false}
return res.json({ ready: false });
} else {
return res.json({ ready: true, locations: clueLocations.sort(() => Math.random() - 0.5) });
}
});
// listen 3003
app.get('/', (req, res) => {
res.status(200).send('WorldGuessr Utils');
});
app.listen(3003, () => {
console.log('WorldGuessr Utils listening on port 3003');
});