File size: 4,430 Bytes
072e993
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import PluginsLoader from './loader.js'
import Plugin from '../plugin.js'
import application from './application.js'
import { WebSocketServer } from 'ws'
import util from 'node:util'
import path from 'node:path'
import http from 'node:http'
import https from 'node:https'

export default class ListenerLoader extends PluginsLoader {
  constructor () {
    global.plugin = Plugin
    super()
  }

  static create (args) {
    let cfg = args.cfg
    if (!cfg.http.HTTPS) {
      args.server = http.createServer(args.app)
    } else {
      args.server = https.createServer(cfg.cert, args.app)
      if (cfg.http.HTTP_TO_HTTPS) {
        http.createServer((req, res) => {
          res.writeHead(307, {
            'Location': cfg.https_address(req.url, req.headers.host)
          }).end()
        }).listen(cfg.http.HTTP_PORT)
      }
    }
    args.handler = application.Handle(args.app)
    args.wss = new WebSocketServer({ server: args.server })
    return Object.assign(new ListenerLoader(), args)
  }

  async run () {
    this.wss.on('error', logger.error)
    this.wss.on('connection', (socket, request) => {
      if ('upgradeReq' in socket) {
        request = socket.upgradeReq
      }
      request.ws = socket
      request.url = this.handler.WebSocketUrl(request.url)
      this.handler.call(request.url.split('?')[0], [socket, request], () => {
        if (!request.wsHandled) socket.close()
      })
    })
    await this.pluginsLoader()
    await this.addListener()
    this.server.listen(...this.cfg.http_listen)
  }

  async addListener () {
    this.cfg.paths = {}
    for (let plugin of this.priority) {
      if (plugin.rule) {
        for (let v of plugin.rule) {
          let middlewares = []

          let path = ((plugin.self.route || '') + (v.path || '')) || '/'

          if (v.use) {
            if (typeof v.use == 'string' && plugin.self[v.use]) {
              let result = await plugin.self[v.use]()
              if (result) {
                if (!util.isArray(result)) {
                  result = [result]
                }
                middlewares.push(...result)
              }
            } else if (util.isArray(v.use)) {
              v.use.forEach(fn => {
                if (fn && plugin.self[fn]) {
                  middlewares.push(plugin.self[fn])
                }
              })
            }
          }

          if (v.fnc && plugin.self[v.fnc]) {
            if (v.method == 'ws') {
              middlewares.push(this.WebSocketEvent(plugin, v.fnc))
            } else {
              middlewares.push(this.HttpRequestEvent(plugin, v.fnc))
            }
          }

          this.app[v.method](path, middlewares)
        }
      }
    }
  }

  HttpRequestEvent (plugin, fnc) {
    return async (req, res, next) => {
      let p = (this.priority.find(val => val.key == plugin.key))?.class
      if (!p) return res.send({ status: 1, message: 'Error occurred!' })
      let t = {
        req, res, next,
        param: req.params,
        query: req.query,
        cookie: req.cookies,
        body: req.body,
        end: res.end,
        send: (data, status) => res.status(status || 200).send(data),
        error: (msg, status) => res.status(status || 200).send({ status: 1, message: msg || 'Invalid request' }),
        render: res.render
      }
      t.params = Object.assign({}, t.param, t.query, t.body, t.cookie)
      let self = Object.assign(new p(), t)
      try {
        let res = self[fnc] && self[fnc]()
        if (util.types.isPromise(res)) {
          res = await res
        }
      } catch (err) {
        if (err) logger.error(err)
      }
    }
  }

  WebSocketEvent (plugin, fnc) {
    return async (socket, request, next) => {
      let p = (this.priority.find(val => val.key == plugin.key))?.class
      if (!p) return socket.close()
      let t = {
        socket, request, next,
        send: (...args) => socket.send(...args),
        close: () => socket.close(),
        onMessage: (fn, on = 'on') => socket[on]('message', fn),
        onClose: (fn, on = 'on') => socket[on]('close', fn),
        onError: (fn, on = 'on') => socket[on]('error', fn)
      }
      let self = Object.assign(new p(), t)
      self.onError(logger.error)
      try {
        let res = self[fnc] && self[fnc]()
        if (util.types.isPromise(res)) {
          res = await res
        }
      } catch (err) {
        if (err) logger.error(err)
      }
    }
  }
}