-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhammer-rpc.js
More file actions
330 lines (282 loc) · 10.9 KB
/
hammer-rpc.js
File metadata and controls
330 lines (282 loc) · 10.9 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
const RPC = require('discord-rpc');
const { exec, spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
// ====== HARDCODED CLIENT ID (DO NOT CHANGE) ======
const CLIENT_ID = '1464543220317814878';
// ====== COLOR SYSTEM ======
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
// Text colors
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
// Bright colors
brightRed: '\x1b[91m',
brightGreen: '\x1b[92m',
brightYellow: '\x1b[93m',
brightBlue: '\x1b[94m',
brightMagenta: '\x1b[95m',
brightCyan: '\x1b[96m',
brightWhite: '\x1b[97m',
// Background colors
bgBlack: '\x1b[40m',
bgRed: '\x1b[41m',
bgGreen: '\x1b[42m',
};
let themeColor = colors.green; // Default
function setTheme(theme) {
const themes = {
'green': colors.brightGreen,
'red': colors.brightRed,
'blue': colors.brightBlue,
'cyan': colors.brightCyan,
'magenta': colors.brightMagenta,
'yellow': colors.brightYellow,
'hacker': colors.green,
'matrix': colors.brightGreen,
'fire': colors.brightRed,
'ice': colors.brightCyan,
'purple': colors.brightMagenta
};
themeColor = themes[theme.toLowerCase()] || colors.brightGreen;
}
function log(text, color = themeColor) {
console.log(`${color}${text}${colors.reset}`);
}
function logError(text) {
console.log(`${colors.brightRed}${text}${colors.reset}`);
}
function logWarning(text) {
console.log(`${colors.brightYellow}${text}${colors.reset}`);
}
function logSuccess(text) {
console.log(`${themeColor}${text}${colors.reset}`);
}
function logInfo(text) {
console.log(`${colors.cyan}${text}${colors.reset}`);
}
// ====== FIX FOR PKG - Find config.json next to EXE ======
function getConfigPath() {
if (process.pkg) {
return path.join(path.dirname(process.execPath), 'config.json');
}
return path.join(__dirname, 'config.json');
}
// ====== CONFIGURATION LOADER ======
// ====== CONFIGURATION LOADER ======
function loadConfig() {
try {
const configPath = getConfigPath();
logInfo(`📂 Looking for config at: ${configPath}`);
if (!fs.existsSync(configPath)) {
logError('❌ config.json not found!');
logError(` Expected location: ${configPath}`);
logError(' Please make sure config.json is in the same folder as the EXE!');
const defaultConfig = {
"_comment": "Hammer Discord RPC Configuration - Edit the values below",
"hammerPath": "D:\\SteamLibrary\\steamapps\\common\\SourceFilmmaker\\game\\bin\\hammer.exe",
"autoLaunchHammer": true,
"updateIntervalSeconds": 15,
"showConsole": true,
"theme": "green",
"_themeOptions": "green, red, blue, cyan, magenta, yellow, matrix, fire, ice, purple, hacker"
};
try {
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
logSuccess('✅ Created default config.json. Please edit it with your settings.');
} catch (err) {
logError('❌ Could not create config.json: ' + err.message);
}
console.log('\nPress any key to exit...');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
return null;
}
const configData = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configData);
// Convert seconds to milliseconds for internal use
config.updateInterval = (config.updateIntervalSeconds || 15) * 1000;
// Set theme from config
if (config.theme) {
setTheme(config.theme);
}
logSuccess('✅ Config loaded successfully!');
// Validate config
if (!config.hammerPath || !fs.existsSync(config.hammerPath)) {
logError('❌ Invalid Hammer path in config.json!');
logError(` Path: ${config.hammerPath}`);
logError(` Config location: ${configPath}`);
logError(' Please update config.json with the correct path.');
console.log('\nPress any key to exit...');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
return null;
}
return config;
} catch (error) {
logError('❌ Error loading config: ' + error.message);
console.log('\nPress any key to exit...');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
return null;
}
}
const config = loadConfig();
if (!config) {
return;
}
const client = new RPC.Client({ transport: 'ipc' });
let startTime = null;
let lastMapName = null;
let hammerLaunched = false;
// ====== HAMMER LAUNCHER ======
function launchHammer() {
if (!config.autoLaunchHammer || hammerLaunched) return;
log('🚀 Launching Hammer Editor...');
try {
const hammerProcess = spawn(config.hammerPath, [], {
detached: true,
stdio: 'ignore'
});
hammerProcess.unref();
hammerLaunched = true;
logSuccess('✅ Hammer launched successfully!');
} catch (error) {
logError('❌ Failed to launch Hammer: ' + error.message);
}
}
// ====== PROCESS DETECTION ======
function getHammerProcessDetails() {
return new Promise((resolve) => {
const command = `powershell "Get-Process hammer -ErrorAction SilentlyContinue | Select-Object MainWindowTitle, Path | ConvertTo-Json"`;
exec(command, (error, stdout) => {
if (error || !stdout.trim()) {
resolve(null);
return;
}
try {
const result = JSON.parse(stdout);
const processes = Array.isArray(result) ? result : [result];
const targetPath = config.hammerPath.toLowerCase();
const targetProcess = processes.find(p => p.Path && p.Path.toLowerCase() === targetPath);
resolve(targetProcess);
} catch (e) {
resolve(null);
}
});
});
}
// ====== MAP NAME EXTRACTOR ======
function extractMapName(windowTitle) {
if (!windowTitle) return null;
let match = windowTitle.match(/\[(.*?)\]/);
if (match && match[1]) return match[1];
match = windowTitle.match(/Hammer\s*-\s*(.+?\.(?:vmf|dvmf))\s*-/i);
if (match && match[1]) {
return path.basename(match[1], path.extname(match[1]));
}
match = windowTitle.match(/([^\\/]+\.(?:d?vmf))/i);
if (match && match[1]) {
return path.basename(match[1], path.extname(match[1]));
}
return null;
}
// ====== PRESENCE UPDATER ======
async function updatePresence() {
try {
const hammerProcess = await getHammerProcessDetails();
if (hammerProcess) {
const title = hammerProcess.MainWindowTitle || "";
const mapName = extractMapName(title);
const isModified = title.includes("*") || title.toLowerCase().includes("modified");
if (mapName && mapName !== lastMapName) {
if (config.showConsole) {
log(`📝 Map changed: ${mapName}`);
}
startTime = Date.now();
lastMapName = mapName;
} else if (!startTime) {
startTime = Date.now();
}
let detailsText = "Idling in Editor";
let stateText = "No Map Loaded";
if (mapName) {
const displayName = mapName.length > 30 ? mapName.substring(0, 27) + "..." : mapName;
detailsText = `Editing: ${displayName}`;
stateText = isModified ? "⚠️ Unsaved Changes" : "Source Filmmaker";
}
client.setActivity({
details: detailsText,
state: stateText,
startTimestamp: startTime,
largeImageKey: 'hammer_icon',
largeImageText: 'Hammer Editor',
smallImageKey: 'sfm_logo',
smallImageText: 'SFM',
instance: false,
buttons: [
{ label: 'Download SFM', url: 'https://store.steampowered.com/app/1840/Source_Filmmaker/' }
]
});
if (config.showConsole) {
logSuccess(`✅ RPC: ${detailsText} | ${stateText}`);
}
} else {
if (startTime) {
if (config.showConsole) {
logWarning("⏸️ Hammer closed - RPC cleared");
}
startTime = null;
lastMapName = null;
client.clearActivity();
}
}
} catch (err) {
logError("❌ RPC Error: " + err.message);
}
}
// ====== MAIN ======
// ====== MAIN ======
client.on('ready', () => {
console.log('');
log('╔════════════════════════════════════╗');
log('║ Hammer Discord RPC - Ready! 🔨 ║');
log('╚════════════════════════════════════╝');
console.log('');
logInfo(`📍 Target: ${config.hammerPath}`);
logInfo(`🔄 Update interval: ${config.updateIntervalSeconds || 15}s`);
logInfo(`🚀 Auto-launch: ${config.autoLaunchHammer ? 'Enabled' : 'Disabled'}`);
logInfo(`🎨 Theme: ${config.theme || 'green'}`);
console.log('');
launchHammer();
updatePresence();
setInterval(updatePresence, config.updateInterval);
});
client.on('error', (err) => {
logError('❌ Discord RPC Error: ' + err.message);
});
process.on('SIGINT', () => {
console.log('');
logWarning('👋 Shutting down gracefully...');
client.clearActivity();
process.exit(0);
});
client.login({ clientId: CLIENT_ID }).catch((err) => {
logError('❌ Failed to connect to Discord: ' + err.message);
logError(' Make sure Discord is running!');
console.log('\nPress any key to exit...');
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
});