-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataSciencePlugin.js
390 lines (331 loc) · 12.4 KB
/
dataSciencePlugin.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
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
// File: dataSciencePlugin.js
const fs = require('fs');
const path = require('path');
// Get the resource path using GetCurrentResourceName()
const resourceName = GetCurrentResourceName();
const resourcePath = GetResourcePath(resourceName);
// Function to find vMenu config file
function findVMenuConfig() {
const baseResourcePath = path.join(resourcePath, '../..');
const vmenuPath = path.join(baseResourcePath, 'vMenu/config/addons.json');
if (fs.existsSync(vmenuPath)) {
console.log(`Found vMenu config at: ${vmenuPath}`);
return vmenuPath;
}
console.error('Error: vMenu config not found at: ' + vmenuPath);
console.error('Please ensure vMenu is installed and has a valid addons.json file.');
throw new Error('Required vMenu config not found');
}
// Add function to clean JSON data
function cleanJsonData(data) {
// Remove comments (lines starting with ##)
const cleanData = data.split('\n')
.filter(line => !line.trim().startsWith('##'))
.join('\n');
// Remove trailing commas and clean up JSON
return cleanData.replace(/,(\s*[}\]])/g, '$1');
}
// Update the vMenu vehicles loading function
function loadVMenuVehicles() {
try {
const configPath = findVMenuConfig();
const rawData = fs.readFileSync(configPath, 'utf8');
const cleanedData = cleanJsonData(rawData);
const vmenuData = JSON.parse(cleanedData);
if (vmenuData && vmenuData.vehicles) {
// Filter out any empty strings or comment markers
const validVehicles = vmenuData.vehicles.filter(v =>
typeof v === 'string' &&
v.trim() !== '' &&
!v.startsWith('##')
);
console.log(`Loaded ${validVehicles.length} vehicles from vMenu config`);
return validVehicles;
}
throw new Error('No vehicles found in vMenu config');
} catch (error) {
console.error('Failed to load vMenu vehicles:', error);
throw error;
}
}
// Store valid vehicles globally
let validVehicles = [];
// Function to initialize valid vehicles
function initializeValidVehicles() {
try {
validVehicles = loadVMenuVehicles();
console.log(`Initialized ${validVehicles.length} valid vehicles for tracking`);
} catch (error) {
console.error('Failed to initialize valid vehicles:', error);
validVehicles = [];
}
}
// Function to check if vehicle should be tracked
function isValidVehicle(vehicleName) {
return validVehicles.includes(vehicleName.toLowerCase());
}
// Remove getDefaultVehicleList function as it's no longer needed
let vehicleData = {};
// Add throttle for saves
let lastSave = 0;
const SAVE_THROTTLE = 5000; // Only save every 5 seconds
// Function to log vehicle spawn
function logVehicleSpawn(vehicleName) {
if (!vehicleData[vehicleName]) {
vehicleData[vehicleName] = { spawns: 0, usageTime: 0 };
}
vehicleData[vehicleName].spawns += 1;
saveVehicleData();
}
// Update log vehicle usage to batch updates
let pendingUpdates = {};
let updateTimeout = null;
const UPDATE_DELAY = 5000; // Process updates every 5 seconds
function logVehicleUsage(vehicleName, usageTime) {
if (!vehicleData[vehicleName]) {
vehicleData[vehicleName] = { spawns: 0, usageTime: 0 };
}
// Accumulate time instead of saving immediately
if (!pendingUpdates[vehicleName]) {
pendingUpdates[vehicleName] = 0;
}
pendingUpdates[vehicleName] += usageTime;
// Set timeout to process updates if not already set
if (!updateTimeout) {
updateTimeout = setTimeout(() => {
processPendingUpdates();
}, UPDATE_DELAY);
}
}
function processPendingUpdates() {
for (const [vehicleName, time] of Object.entries(pendingUpdates)) {
vehicleData[vehicleName].usageTime += time;
}
pendingUpdates = {};
updateTimeout = null;
saveVehicleData();
}
// Function to get sorted vehicle data
function getSortedVehicleData() {
return Object.entries(vehicleData)
.sort((a, b) => {
// First sort by number of spawns
const spawnDiff = b[1].spawns - a[1].spawns;
if (spawnDiff !== 0) return spawnDiff;
// If spawns are equal, sort by usage time
return b[1].usageTime - a[1].usageTime;
})
.map(([vehicleName, data]) => ({ vehicleName, ...data }));
}
// Function to save vehicle data to a file - update with throttling
function saveVehicleData() {
try {
const now = Date.now();
if (now - lastSave < SAVE_THROTTLE) return; // Skip if too soon
if (!resourcePath) {
throw new Error('Resource path not available');
}
lastSave = now;
const dataPath = path.join(resourcePath, 'vehicleData.json');
fs.writeFileSync(dataPath, JSON.stringify(vehicleData, null, 2));
// Only generate HTML report when explicitly requested or during hourly updates
// Remove automatic HTML generation here
} catch (error) {
console.error('Failed to save vehicle data:', error);
}
}
// Function to load vehicle data from a file - update with error handling
function loadVehicleData() {
try {
if (!resourcePath) {
throw new Error('Resource path not available');
}
const dataPath = path.join(resourcePath, 'vehicleData.json');
if (fs.existsSync(dataPath)) {
vehicleData = JSON.parse(fs.readFileSync(dataPath));
console.log('Vehicle data loaded successfully');
}
} catch (error) {
console.error('Failed to load vehicle data:', error);
}
}
// Function to format time
function formatTime(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainingSeconds = (seconds % 60).toFixed(0);
if (hours > 0) {
return `${hours}h ${minutes}m ${remainingSeconds}s`;
} else if (minutes > 0) {
return `${minutes}m ${remainingSeconds}s`;
}
return `${remainingSeconds}s`;
}
// Function to generate HTML report
function generateHTMLReport() {
try {
const sortedData = getSortedVehicleData();
let content = 'Vehicle Usage Statistics\n\n';
content += 'Vehicle Name | Times Spawned | Total Drive Time\n';
content += '------------|---------------|----------------\n';
if (sortedData.length > 0) {
sortedData.forEach(v => {
const formattedTime = formatTime(v.usageTime || 0);
content += `${v.vehicleName} | ${v.spawns || 0} | ${formattedTime}\n`;
});
} else {
content += 'No vehicle data recorded yet\n';
}
const htmlPath = path.join(resourcePath, 'stats.html');
fs.writeFileSync(htmlPath, content);
console.log(`Simple stats report generated at: ${htmlPath}`);
} catch (error) {
console.error('Failed to generate stats report:', error);
}
}
// Register network event handlers
onNet('vehdatascience:vehicleSpawned', (vehicleName) => {
if (isValidVehicle(vehicleName)) {
logVehicleSpawn(vehicleName);
}
});
onNet('vehdatascience:vehicleUsed', (vehicleName, usageTime) => {
if (isValidVehicle(vehicleName)) {
logVehicleUsage(vehicleName, usageTime);
}
});
// Add handlers for server.lua events
on('vehdatascience:saveVehicleUsage', (vehicleName, usageTime) => {
logVehicleUsage(vehicleName, usageTime);
});
on('vehdatascience:logVehicleSpawn', (vehicleName) => {
logVehicleSpawn(vehicleName);
});
// Update the command handler to include all vehicles
onNet('vehdatascience:requestStats', () => {
const source = global.source;
try {
const sortedData = getSortedVehicleData();
const statsForNui = sortedData.map(v => ({
vehicleName: v.vehicleName,
spawns: v.spawns || 0,
formattedTime: formatTime(v.usageTime || 0)
}));
// Get the complete vehicle list from vMenu
const allVehicles = loadVMenuVehicles();
emitNet('vehdatascience:receiveStats', source, {
stats: statsForNui,
allVehicles: allVehicles
});
console.log('Vehicle stats sent to client');
} catch (error) {
console.error('Error preparing stats for NUI:', error);
}
});
// Register command to show stats in chat
RegisterCommand('vehiclestats', (source, args) => {
try {
const sortedData = getSortedVehicleData();
const top10 = sortedData.slice(0, 10);
emitNet('chat:addMessage', source, {
args: ['Vehicle Statistics - Top 10']
});
if (top10.length === 0) {
emitNet('chat:addMessage', source, {
args: ['No vehicle data recorded yet']
});
return;
}
top10.forEach(vehicle => {
const spawns = vehicle.spawns || 0;
const usageTime = vehicle.usageTime || 0;
emitNet('chat:addMessage', source, {
args: [`${vehicle.vehicleName}: Spawns: ${spawns}, Usage: ${usageTime.toFixed(2)}s`]
});
});
generateHTMLReport();
console.log('Vehicle stats command executed successfully');
} catch (error) {
console.error('Error in vehiclestats command:', error);
emitNet('chat:addMessage', source, {
args: ['Error retrieving vehicle statistics']
});
}
}, false);
// Add reset function
// Update reset function to notify clients
function resetVehicleData() {
vehicleData = {};
saveVehicleData();
emitNet('vehdatascience:resetStats', -1); // -1 sends to all clients
console.log('Vehicle statistics have been reset');
}
// Add reset command
RegisterCommand('vehiclestatsreset', (source, args) => {
try {
// Only allow server console and admins to reset stats
if (source === 0) { // Console
resetVehicleData();
console.log('Vehicle statistics reset by console');
} else {
// Check if player is admin (you may want to modify this based on your permission system)
if (IsPlayerAceAllowed(source.toString(), 'command.vehiclestatsreset')) {
resetVehicleData();
emitNet('chat:addMessage', source, {
args: ['Vehicle statistics have been reset']
});
console.log(`Vehicle statistics reset by player ID: ${source}`);
} else {
emitNet('chat:addMessage', source, {
args: ['You do not have permission to reset vehicle statistics']
});
}
}
} catch (error) {
console.error('Error in vehiclestatsreset command:', error);
if (source !== 0) {
emitNet('chat:addMessage', source, {
args: ['Error resetting vehicle statistics']
});
}
}
}, true); // restricted - only available to players with proper permissions
// Load vehicle data on startup
loadVehicleData();
generateHTMLReport(); // Generate HTML on startup
// Create stats.html if it doesn't exist
if (!fs.existsSync(path.join(resourcePath, 'stats.html'))) {
generateHTMLReport();
}
// Add console confirmation
console.log('Vehicle Data Science Plugin loaded. Stats available at stats.html');
// Add hourly stats generation
const HOUR_IN_MS = 60 * 60 * 1000;
function generateHourlyStats() {
try {
const sortedData = getSortedVehicleData();
generateHTMLReport();
console.log('Hourly vehicle stats generated automatically');
// Schedule next update in 1 hour
setTimeout(generateHourlyStats, HOUR_IN_MS);
} catch (error) {
console.error('Error in hourly stats generation:', error);
// If there's an error, try again in 1 hour
setTimeout(generateHourlyStats, HOUR_IN_MS);
}
}
// Start the hourly updates
setTimeout(generateHourlyStats, HOUR_IN_MS);
console.log('Automatic hourly stats generation enabled');
// Replace config.json loading with vMenu config
const vehicles = loadVMenuVehicles();
console.log(`Loaded ${vehicles.length} vehicles ${vehicles.length > 0 ? 'from config' : 'using defaults'}`);
// Initialize valid vehicles on resource start
initializeValidVehicles();
// Export functions for use in other scripts
module.exports = {
logVehicleSpawn,
logVehicleUsage,
getSortedVehicleData,
saveVehicleData
};