-
Notifications
You must be signed in to change notification settings - Fork 24
/
client.ts
97 lines (86 loc) · 2.63 KB
/
client.ts
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
import { EventEmitter } from 'events'
import { authenticate, ClientNotFoundError, Credentials } from './authentication.js'
const DEFAULT_POLL_INTERVAL = 2500
export declare interface LeagueClient {
on(event: 'connect', callback: (credentials: Credentials) => void): this
on(event: 'disconnect', callback: () => void): this
}
export interface LeagueClientOptions {
/**
* The time duration in milliseconds between each check for a client
* disconnect
*
* Default: 2500
*/
pollInterval: number
}
export class LeagueClient extends EventEmitter {
private isListening: boolean = false
public credentials?: Credentials = undefined
constructor(credentials: Credentials, public options?: LeagueClientOptions) {
super()
this.credentials = credentials
}
/**
* Start listening for League Client processes
*/
start() {
// Only trigger if it's not already
// running
if (!this.isListening) {
this.isListening = true
if (this.credentials === undefined || !processExists(this.credentials.pid)) {
// Invalidated credentials or no LeagueClientUx process, fail
throw new ClientNotFoundError()
}
this.onTick()
}
}
/**
* Stop listening for client stop/start
*/
stop() {
this.isListening = false
}
private async onTick() {
if (this.isListening) {
if (this.credentials !== undefined) {
// Current credentials are valid
if (!processExists(this.credentials.pid)) {
// No such process, emit disconnect and
// invalidate credentials
this.emit('disconnect')
this.credentials = undefined
// Re-queue onTick to listen for credentials
this.onTick()
} else {
// Process still lives, queue onTick
setTimeout(() => {
this.onTick()
}, this.options?.pollInterval ?? DEFAULT_POLL_INTERVAL)
}
} else {
// Current credentials were invalidated, wait for
// client to come back up
const credentials = await authenticate({
awaitConnection: true,
pollInterval: this.options?.pollInterval ?? DEFAULT_POLL_INTERVAL
})
this.credentials = credentials
this.emit('connect', credentials)
setTimeout(() => {
this.onTick()
}, this.options?.pollInterval ?? DEFAULT_POLL_INTERVAL)
}
}
}
}
function processExists(pid: number): boolean {
try {
// `man 1 kill`: if sig is 0, then no signal is sent, but error checking
// is still performed.
return process.kill(pid, 0)
} catch (err: unknown) {
return (err as any)?.code === 'EPERM'
}
}