summary refs log tree commit diff homepage
path: root/src/MinecraftHandler.ts
blob: 79ad81b6abe8d475f8140a057e9bc3aa8d7ed7d1 (plain) (blame)
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
import fs from 'fs'
import { Tail } from 'tail'
import express from 'express'

import { Config } from './Config'

export type LogLine = {
  username: string
  message: string
} | null

type Callback = (data: LogLine) => void

class MinecraftHandler {
  config: Config

  app: express.Application
  tail: Tail

  constructor(config: Config) {
    this.config = config
  }

  fixMinecraftUsername (username: string) {
    return username.replace(/(§[A-Z-a-z0-9])/g, '')
  }

  private parseLogLine (data: string): LogLine {
    const ignored = new RegExp(this.config.REGEX_IGNORED_CHAT)

    if (ignored.test(data) || data.includes('Rcon connection')) {
      if (this.config.DEBUG) console.log('[DEBUG] Line ignored')
      return null
    }

    if (this.config.DEBUG) console.log('[DEBUG] Received ' + data)

    const logLineDataRegex = new RegExp(
      `${(this.config.REGEX_SERVER_PREFIX || "\\[Server thread/INFO\\]:")} (.*)`
    )

    // get the part after the log prefix, so all the actual data is here
    const logLineData = data.match(logLineDataRegex)

    if (!logLineDataRegex.test(data) || !logLineData) {
      console.log('[ERROR] Regex could not match the string! Please verify it is correct!')
      console.log('Received: "' + data + '", Regex matches lines that start with: "' + this.config.REGEX_SERVER_PREFIX + '"')
      return null
    }

    const logLine = logLineData[1]

    const serverUsername = `${this.config.SERVER_NAME} - Server`

    if (logLine.startsWith('<')) {
      if (this.config.DEBUG){
        console.log('[DEBUG]: A player sent a chat message')
      }

      const re = new RegExp(this.config.REGEX_MATCH_CHAT_MC)
      const matches = logLine.match(re)

      if (!matches) {
        console.log('[ERROR] Could not parse message: ' + logLine)
        return null
      }

      const username = this.fixMinecraftUsername(matches[1])
      const message = matches[2]
      if (this.config.DEBUG) {
        console.log('[DEBUG] Username: ' + matches[1])
        console.log('[DEBUG] Text: ' + matches[2])
      }
      return { username, message }
    } else if (
      this.config.SHOW_PLAYER_CONN_STAT && (
        logLine.includes('left the game') ||
        logLine.includes('joined the game')
      )
    ) {
      // handle disconnection etc.
      if (this.config.DEBUG){
        console.log(`[DEBUG]: A player's connection status changed`)
      }

      return { username: serverUsername, message: logLine }
    } else if (this.config.SHOW_PLAYER_ADVANCEMENT && logLine.includes('made the advancement')) {
      // handle advancements
      if (this.config.DEBUG){
        console.log('[DEBUG] A player has made an advancement')
      }
      return { username: `${this.config.SERVER_NAME} - Server`, message: logLine }
    } else if (this.config.SHOW_PLAYER_ME && logLine.startsWith('* ')) {
      // /me commands have the bolded name and the action they did
      const usernameMatch = data.match(/: \* ([a-zA-Z0-9_]{1,16}) (.*)/)
      if (usernameMatch) {
        const username = usernameMatch[1]
        const rest = usernameMatch[2]
        return { username: serverUsername, message: `**${username}** ${rest}` }
      }
    } else if (this.config.SHOW_PLAYER_DEATH) {
      for (let word of this.config.DEATH_KEY_WORDS){
        if (data.includes(word)){
          if (this.config.DEBUG) {
            console.log(
              `[DEBUG] A player died. Matched key word "${word}"`
            )
          }
          return { username: serverUsername, message: logLine }
        }
      }
    }

    return null
  }

  private initWebServer (callback: Callback) {
    // init the webserver
    this.app = express()
    const http = require('http').Server(this.app)

    this.app.use((request: express.Request, response: express.Response, next: express.NextFunction) => {
      request.rawBody = ''
      request.setEncoding('utf8')

      request.on('data', (chunk: string) => {
        request.rawBody += chunk
      })

      request.on('end', function () {
        next()
      })
    })

    this.app.post(this.config.WEBHOOK, (req, res) => {
      if (req.rawBody) {
        const logLine = this.parseLogLine(req.rawBody)
        callback(logLine)
      }
      res.json({ received: true })
    })

    const port = process.env.PORT || this.config.PORT

    http.listen(port, () => {
      console.log('[INFO] Bot listening on *:' + port)

      if (!this.config.IS_LOCAL_FILE && this.config.SHOW_INIT_MESSAGE) {
        console.log('[INFO] Please enter the following command on your server running the Minecraft server.')
        console.log('       Replace "PATH_TO_MINECRAFT_SERVER_INSTALL" with the path to your Minecraft server install')
        console.log('       and "YOUR_URL" with the URL/IP of the server running Shulker!')
        console.log(`  \`tail -F /PATH_TO_MINECRAFT_SERVER_INSTALL/logs/latest.log | grep --line-buffered "${this.config.REGEX_SERVER_PREFIX}" | while read x ; do echo -ne $x | curl -X POST -d @- http://YOUR_URL:${port}${this.config.WEBHOOK} ; done\``)
      }
    })
  }

  private initTail (callback: Callback) {
    if (fs.existsSync(this.config.LOCAL_FILE_PATH)) {
      console.log(`[INFO] Using configuration for local file at "${this.config.LOCAL_FILE_PATH}"`)
      this.tail = new Tail(this.config.LOCAL_FILE_PATH)
    } else {
      throw new Error(`[ERROR] Local file not found at "${this.config.LOCAL_FILE_PATH}"`)
    }
    this.tail.on('line', (data: string) => {
      // Parse the line to see if we care about it
      let logLine = this.parseLogLine(data)
      if (data) {
        callback(logLine)
      }
    })
    this.tail.on('error', (error: any) => {
      console.log('[ERROR] Error tailing file: ' + error)
    })
  }

  init (callback: Callback) {
    if (this.config.IS_LOCAL_FILE) {
      this.initTail(callback)
    } else {
      this.initWebServer(callback)
    }
  }
}

export default MinecraftHandler