-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminalControl.js
More file actions
296 lines (257 loc) · 8.46 KB
/
Copy pathterminalControl.js
File metadata and controls
296 lines (257 loc) · 8.46 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
'use strict';
const readline = require('readline');
const log = require('./logger');
const fs = require('fs');
const path = require('path');
const { LOG_FILE } = require('./paths');
const { getTotals } = require('./totals');
const { getLastCompletedBonuses } = require('./runState');
let activeControl = null;
function formatStatusScreen(lines) {
const safeLines = Array.isArray(lines) ? lines : String(lines).split('\n');
const width = safeLines.reduce((max, line) => Math.max(max, line.length), 0);
const border = '═'.repeat(width + 4);
const framed = safeLines.map(line => `║ ${line.padEnd(width, ' ')} ║`).join('\n');
return `╔${border}╗\n${framed}\n╚${border}╝`;
}
class TaskInterrupted extends Error {
constructor(command = 'stop') {
super(`Task interrupted by terminal command: ${command}`);
this.name = 'TaskInterrupted';
this.command = command;
}
}
class TaskRestarted extends Error {
constructor(command = 'restart') {
super(`Task interrupted by terminal command: ${command}`);
this.name = 'TaskRestarted';
this.command = command;
}
}
function isTaskInterrupted(err) {
return err instanceof TaskInterrupted || err?.name === 'TaskInterrupted' || err instanceof TaskRestarted || err?.name === 'TaskRestarted';
}
function isTaskRestarted(err) {
return err instanceof TaskRestarted || err?.name === 'TaskRestarted';
}
function getActiveControl() {
return activeControl?.closed ? null : activeControl;
}
class TerminalControl {
constructor(options = {}) {
this.tag = options.tag || 'control';
this.status = options.status || null;
this.allowRunNow = options.allowRunNow ?? false;
this.stopRequested = false;
this.runNowRequested = false;
this.restartRequested = false;
this.closed = false;
this.stopWaiters = new Set();
this.runNowWaiters = new Set();
this.restartWaiters = new Set();
this.readline = null;
this.ownsReadline = false;
this.lineHandler = line => this.handleLine(line);
}
helpText() {
const commands = [
'c/clean = clear all past logs',
'l/log = show log counters and last 5 bonuses',
'r/restart = refresh and run again with a new login',
's/status = show current state',
'h/help = show commands',
'q/quit = stop after the current browser action',
];
if (this.allowRunNow) commands.splice(4, 0, 'run/now = start the next scheduled run now');
return ['Commands while running:', ...commands].join('\n ');
}
printHelp() {
console.log(`\n[${this.tag}]\n ${this.helpText()}\n`);
}
attachReadline(rl) {
this.readline = rl;
this.ownsReadline = false;
activeControl = this;
rl.on('line', this.lineHandler);
this.printHelp();
return () => this.detach();
}
attachStdin() {
if (!process.stdin.isTTY) return () => {};
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
this.readline = rl;
this.ownsReadline = true;
activeControl = this;
rl.on('line', this.lineHandler);
this.printHelp();
return () => this.detach();
}
detach() {
if (this.closed) return;
this.closed = true;
if (this.readline) {
this.readline.off('line', this.lineHandler);
if (this.ownsReadline) {
this.readline.close();
}
}
if (activeControl === this) activeControl = null;
this.stopWaiters.clear();
this.runNowWaiters.clear();
}
handleLine(raw) {
const command = raw.trim().toLowerCase();
if (!command) return;
if (command === 'clean' || command === 'c') {
const logFile = LOG_FILE;
try {
fs.writeFileSync(logFile, '');
console.log(`\n[${this.tag}] Log file cleared.\n`);
} catch (err) {
console.log(`\n[${this.tag}] Failed to clear log file: ${err.message}\n`);
}
return;
}
if (command === 'log' || command === 'l') {
const totals = getTotals();
const lastBonuses = getLastCompletedBonuses(5);
const lines = [
'Log Counters:',
` Hero Time Bonuses: ${totals.heroTimeBonuses}`,
` Hero Danger Bonuses: ${totals.heroDangerBonuses}`,
` Wood Bonuses: ${totals.woodBonuses}`,
` Clay Bonuses: ${totals.clayBonuses}`,
` Iron Bonuses: ${totals.ironBonuses}`,
` Crop Bonuses: ${totals.cropBonuses}`,
` Farm list sends: ${totals.farmListSends ?? 0}`,
'',
'Last 5 Successful Bonuses:',
...lastBonuses.map((bonus, i) => ` ${i + 1}. [${bonus.timestamp}] ${bonus.message}`),
];
console.log(`\n${formatStatusScreen(lines)}\n`);
return;
}
if (command === 'restart' || command === 'r') {
this.requestRestart();
return;
}
if (command === 'status' || command === 's') {
const statusResult = this.status ? this.status() : 'Task is running';
const statusLines = Array.isArray(statusResult)
? statusResult
: String(statusResult).split('\n');
console.log(`\n${formatStatusScreen(statusLines)}\n`);
return;
}
if (this.allowRunNow && (command === 'run' || command === 'now')) {
this.requestRunNow();
return;
}
if (command === 'help' || command === 'h') {
this.printHelp();
return;
}
if (command === 'quit' || command === 'q') {
this.requestStop(command);
return;
}
console.log(`\n[${this.tag}] Unknown command: ${command}. Type help.\n`);
}
requestStop(command = 'stop') {
if (this.stopRequested) return;
this.stopRequested = true;
for (const reject of this.stopWaiters) reject(new TaskInterrupted(command));
this.stopWaiters.clear();
}
requestRunNow() {
this.runNowRequested = true;
log.info(this.tag, 'Terminal command requested run now');
for (const resolve of this.runNowWaiters) resolve('run');
this.runNowWaiters.clear();
}
requestRestart() {
if (this.restartRequested) return;
this.restartRequested = true;
log.info(this.tag, 'Terminal command requested restart');
for (const resolve of this.restartWaiters) resolve('restart');
this.restartWaiters.clear();
}
throwIfStopped() {
if (this.stopRequested) throw new TaskInterrupted('stop');
}
waitForStop() {
if (this.stopRequested) return Promise.reject(new TaskInterrupted('stop'));
if (this.restartRequested) return Promise.reject(new TaskRestarted('restart'));
return new Promise((_, reject) => this.stopWaiters.add(reject));
}
race(promise) {
if (this.stopRequested) return Promise.reject(new TaskInterrupted('stop'));
if (this.restartRequested) return Promise.reject(new TaskRestarted('restart'));
let stopReject;
let restartReject;
const stopPromise = new Promise((_, reject) => {
stopReject = reject;
this.stopWaiters.add(stopReject);
});
const restartPromise = new Promise((_, reject) => {
restartReject = reject;
this.restartWaiters.add(restartReject);
});
return Promise.race([promise, stopPromise, restartPromise])
.finally(() => {
this.stopWaiters.delete(stopReject);
this.restartWaiters.delete(restartReject);
});
}
async wait(ms) {
this.throwIfStopped();
if (this.runNowRequested) {
this.runNowRequested = false;
return 'run';
}
if (this.restartRequested) {
this.restartRequested = false;
return 'restart';
}
let stopReject;
let runResolve;
let restartResolve;
const stopPromise = new Promise((_, reject) => {
stopReject = reject;
this.stopWaiters.add(stopReject);
});
const runPromise = new Promise(resolve => {
runResolve = resolve;
this.runNowWaiters.add(runResolve);
});
const restartPromise = new Promise(resolve => {
restartResolve = resolve;
this.restartWaiters.add(restartResolve);
});
return Promise.race([
new Promise(resolve => setTimeout(() => resolve('timeout'), ms)),
stopPromise,
runPromise,
restartPromise,
]).then(result => {
if (result === 'run') this.runNowRequested = false;
if (result === 'restart') this.restartRequested = false;
return result;
}).finally(() => {
this.stopWaiters.delete(stopReject);
this.runNowWaiters.delete(runResolve);
this.restartWaiters.delete(restartResolve);
});
}
}
function createTerminalControl(options) {
return new TerminalControl(options);
}
module.exports = {
TaskInterrupted,
TaskRestarted,
createTerminalControl,
getActiveControl,
isTaskInterrupted,
isTaskRestarted,
};