-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupdate-default-data.js
More file actions
174 lines (139 loc) · 5.45 KB
/
update-default-data.js
File metadata and controls
174 lines (139 loc) · 5.45 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
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const apiPath = 'https://nomanssky.fandom.com/api.php';
let MIN_REQUEST_INTERVAL = 35000; // default, it will be changed if the rate limit is modified
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const filterValidData = (data) => {
return data.filter(item =>
item.title.civilizeD &&
item.title.civilizeD !== 'Uncharted' &&
item.title.coordinateS &&
item.title.galaxY &&
item.title.pageName
);
};
const getRateLimit = async () => {
const url = `${apiPath}?action=query&meta=userinfo&uiprop=ratelimits&format=json&origin=*`;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP error getting rate limit: ${res.status}`);
const data = await res.json();
const cargoLimits = data?.query?.userinfo?.ratelimits?.["cargo-query"];
if (!cargoLimits) return MIN_REQUEST_INTERVAL;
let maxInterval = 0;
for (const key in cargoLimits) {
const limit = cargoLimits[key]; // { hits, seconds }
if (limit.hits && limit.seconds) {
const interval = limit.seconds / limit.hits;
if (interval > maxInterval) maxInterval = interval;
}
}
const intervalMs = Math.ceil(maxInterval * 1000) + 5000;
console.log(`Cargo-query rate limits: ${JSON.stringify(cargoLimits)}, using interval ${intervalMs}ms`);
return intervalMs;
};
const fetchCivilizationsPage = async (offset = 0) => {
const params = new URLSearchParams();
params.append('action', 'cargoquery');
params.append('tables', 'Regions');
params.append('fields', 'Regions.Civilized=civilizeD,Regions.Galaxy=galaxY,Regions.Coordinates=coordinateS,_pageName=pageName');
params.append('group_by', '_pageName');
params.append('order_by', '_pageName');
params.append('limit', '500');
params.append('offset', offset.toString());
params.append('format', 'json');
params.append('origin', '*');
params.append('where', 'Civilized IS NOT NULL AND Civilized <> "Uncharted" AND Coordinates IS NOT NULL AND Galaxy IS NOT NULL');
const url = `${apiPath}?${params.toString()}`;
console.log(`Fetching page with offset: ${offset}`);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
return data.cargoquery || [];
};
const fetchAllCivilizationsAndRegions = async () => {
console.log('Starting data fetch...');
let allData = [];
let offset = 0;
let hasMore = true;
let requestCount = 0;
while (hasMore) {
try {
const pageData = await fetchCivilizationsPage(offset);
const validPageData = filterValidData(pageData);
console.log(`Page ${requestCount + 1}: ${pageData.length} raw items, ${validPageData.length} valid items`);
if (pageData.length === 0) {
hasMore = false;
console.log('No more data available');
} else {
allData = allData.concat(validPageData);
requestCount++;
console.log(`Total valid items so far: ${allData.length}`);
if (pageData.length < 500) {
hasMore = false;
console.log('Last page reached');
} else {
offset += 500;
console.log(`Waiting ${MIN_REQUEST_INTERVAL}ms before next request...`);
await sleep(MIN_REQUEST_INTERVAL);
}
}
} catch (error) {
console.error('Error fetching page:', error);
throw error;
}
}
console.log(`Total valid items fetched: ${allData.length}`);
if (allData.length > 0) {
const galaxies = [...new Set(
allData.map(item => item.title.galaxY)
)].filter(Boolean).sort();
const data = {};
galaxies.forEach(galaxy => {
data[galaxy] = {
civilizations: [],
regions: {}
};
const galaxyData = allData.filter(item => item.title.galaxY === galaxy);
const civilizations = [...new Set(
galaxyData.map(item => item.title.civilizeD)
)].sort();
data[galaxy].civilizations = civilizations;
civilizations.forEach(civ => {
data[galaxy].regions[civ] = galaxyData
.filter(item => item.title.civilizeD === civ)
.map(item => ({
name: item.title.pageName,
coordinates: item.title.coordinateS,
}))
.sort((a, b) => a.name.localeCompare(b.name));
});
});
return { galaxies, data };
} else {
throw new Error('No valid data could be fetched');
}
};
const main = async () => {
try {
console.log('=== Starting defaultData.json update ===');
MIN_REQUEST_INTERVAL = await getRateLimit();
const result = await fetchAllCivilizationsAndRegions();
const outputPath = path.join(__dirname, '../../public/assets/defaultData/defaultData.json');
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
fs.writeFileSync(outputPath, JSON.stringify(result, null, 2));
console.log(`=== Data successfully saved to ${outputPath} ===`);
console.log(`Total galaxies: ${result.galaxies.length}`);
console.log(`Total civilizations: ${Object.values(result.data).reduce((sum, g) => sum + g.civilizations.length, 0)}`);
} catch (error) {
console.error('=== Error updating data ===');
console.error(error);
process.exit(1);
}
};
main();