Completed
Push — master ( 59cd4c...8588a0 )
by Dimas
10:00
created

libs/src/UI/index.ts   A

Complexity

Total Complexity 19
Complexity/F 9.5

Size

Lines of Code 183
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 140
dl 0
loc 183
rs 10
c 0
b 0
f 0
wmc 19
mnd 17
bc 17
fnc 2
bpm 8.5
cpm 9.5
noi 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
C index.ts ➔ serve 0 79 7
D index.ts ➔ template 0 66 12
1
import * as fs from "fs";
2
import * as path from "path";
3
import * as Process from "process";
4
import * as http from "http";
5
import { readFile, list_package, asset } from "../compiler/func";
6
import app from "express";
7
import io from "socket.io";
8
import * as url_core from "url";
9
10
console.clear();
11
var config: {
12
  app: {
13
    root: string;
14
    domain: string;
15
    protocol: string;
16
    views: string;
17
    environtment: "production" | "development";
18
  };
19
} = null;
20
21
try {
22
  if (fs.existsSync("./config.json")) {
23
    config = JSON.parse(fs.readFileSync("./config.json").toString());
24
  } else if (fs.existsSync(Process.cwd() + "/config.json")) {
25
    config = require(Process.cwd() + "/config.json");
26
  }
27
} catch (e) {}
28
29
if (!config) {
30
  console.error("config.json could not be found");
31
  throw new Error("config.json could not be found");
32
}
33
34
export /**
35
 *
36
 * @param title
37
 * @param content
38
 * @param param
39
 */
40
function template(
41
  title:
42
    | string
43
    | ((arg0: http.IncomingMessage, arg1: http.ServerResponse) => string),
44
  content?: [http.IncomingMessage, http.ServerResponse] | string,
45
  param?: [http.IncomingMessage, http.ServerResponse]
46
) {
47
  var status = 200;
48
49
  if (typeof title == "string") {
50
    var template = fs
51
      .readFileSync("./assets/node/template/mdb.html")
52
      .toString();
53
54
    var body = `./assets/node/views/${content}.html`;
55
    if (fs.existsSync(body)) {
56
      template = template.replace(
57
        /\%content\%/gm,
58
        fs.readFileSync(body).toString()
59
      );
60
    } else {
61
      console.warn("body not found");
62
      status = 404;
63
      template = template.replace(
64
        /\%content\%/gm,
65
        readFile(asset("./assets/node/views/404.html"))
66
      );
67
    }
68
    var script = `./assets/node/views/${content}.js`;
69
    if (fs.existsSync(script)) {
70
      template = template.replace(
71
        /\%script\%/gm,
72
        `<script src="${config.app.protocol}://${
73
          config.app.domain
74
        }/assets/node/views/${content}.js${
75
          config.app.environtment == "development"
76
            ? "?cache=" + new Date().getTime()
77
            : ""
78
        }"></script>`
79
      );
80
    } else {
81
      console.log("script not found");
82
    }
83
    param[1].writeHead(status, { "Content-Type": "text/html" });
84
85
    template = template.replace(/\%protocol\%/gm, config.app.protocol);
86
    template = template.replace(/\%domain\%/gm, config.app.domain);
87
    template = template.replace(/\%title\%/gm, title);
88
    template = template.replace(/\%config\%/gm, JSON.stringify(config));
89
    return template;
90
  } else if (typeof title == "function") {
91
    if (Array.isArray(content)) {
92
      content[1].writeHead(status, { "Content-Type": "application/json" });
93
      return title(content[0], content[1]);
94
    } else if (Array.isArray(param)) {
95
      param[1].writeHead(status, { "Content-Type": "application/json" });
96
      return title(param[0], param[1]);
97
    } else {
98
      return "Can't process anything :(";
99
    }
100
  }
101
}
102
export function serve(port: number = 3000) {
103
  const httpServer = http.createServer(function (req, res) {
104
    var url = req.url;
105
    //console.log(url);
106
    var routerStatic = path.join(__dirname, `/components/router/${url}.js`);
107
    //console.log(routerStatic, fs.existsSync(routerStatic));
108
109
    if (url === "/") {
110
      res.write(template("Homepage", "index", [req, res])); //write a response
111
    } else if (url === "/fetch") {
112
      res.write(
113
        template(
114
          function () {
115
            var installed = "./tmp/npm/local.json";
116
            var result = {};
117
            try {
118
              if (fs.existsSync(installed)) {
119
                result = JSON.parse(fs.readFileSync(installed).toString());
120
              } else {
121
                list_package();
122
                result = {
123
                  error: "package still not fetched",
124
                  local: {},
125
                  global: {},
126
                };
127
              }
128
            } catch (error) {
129
              if (error) {
130
                result = {};
131
              }
132
            }
133
134
            return JSON.stringify(result, null, 2);
135
          },
136
          [req, res]
137
        )
138
      ); //write a response
139
    } else if (fs.existsSync(routerStatic)) {
140
      var router = require(path.join(__dirname, "/components/router", url))
141
        .router;
142
      res.write(template(router(), [req, res]));
143
    } else {
144
      res.writeHead(302, {
145
        Location: `${config.app.protocol}://${config.app.domain}/${
146
          url_core.parse(url).pathname
147
        }`,
148
        //add other headers here...
149
      });
150
    }
151
152
    res.end(); //end the response
153
  });
154
155
  const webSocket = io(httpServer);
156
  webSocket.on("connect", (socket) => {
157
    console.log("websocket connected", socket.id);
158
  });
159
  var numClients = 0;
160
  webSocket.on("connection", function (socket) {
161
    numClients++;
162
    socket.emit("stats", { numClients: numClients });
163
164
    console.log("Connected clients:", numClients);
165
166
    socket.on("disconnect", function () {
167
      numClients--;
168
      socket.emit("stats", { numClients: numClients });
169
170
      console.log("Connected clients:", numClients);
171
    });
172
173
    socket.emit("announcements", { message: "A new user has joined!" });
174
    socket.on("fetch", function (data) {
175
      list_package();
176
    });
177
  });
178
179
  httpServer.listen(port, function () {
180
    console.log("server start at port " + port);
181
  });
182
}
183