summaryrefslogtreecommitdiff
path: root/bot/src/commands/lua.cpp
blob: f11bc9e5e67822e0754e4d53b55880d9d9e8eb3b (plain)
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
297
298
299
300
301
302
303
304
#include "commands/lua.hpp"

#include <algorithm>
#include <cmath>
#include <memory>
#include <nlohmann/json.hpp>
#include <sol/sol.hpp>
#include <stdexcept>
#include <string>
#include <vector>

#include "api/twitch/schemas/user.hpp"
#include "bundle.hpp"
#include "commands/request.hpp"
#include "commands/response.hpp"
#include "commands/response_error.hpp"
#include "schemas/user.hpp"
#include "utils/chrono.hpp"
#include "utils/string.hpp"

namespace bot::command::lua {
  namespace library {
    void add_bot_library(std::shared_ptr<sol::state> state) {
      state->set_function("bot_get_compiler_version", []() {
        std::string info;
#ifdef __cplusplus
        info.append("C++" + std::to_string(__cplusplus).substr(2, 2));
#endif
#ifdef __VERSION__
        info.append(" (gcc " +
                    bot::utils::string::split_text(__VERSION__, ' ')[0] + ")");
#endif
        return info;
      });

      state->set_function("bot_get_uptime", []() {
        auto now = std::chrono::steady_clock::now();
        auto duration = now - START_TIME;
        auto seconds =
            std::chrono::duration_cast<std::chrono::seconds>(duration).count();
        return static_cast<long long>(seconds);
      });

      state->set_function("bot_get_memory_usage", []() {
        struct rusage usage;
        getrusage(RUSAGE_SELF, &usage);
        return usage.ru_maxrss;
      });

      state->set_function("bot_get_compile_time",
                          []() { return BOT_COMPILED_TIMESTAMP; });

      state->set_function("bot_get_version", []() { return BOT_VERSION; });
    }

    void add_time_library(std::shared_ptr<sol::state> state) {
      state->set_function("time_current", []() {
        return static_cast<long long>(
            std::chrono::duration_cast<std::chrono::seconds>(
                std::chrono::steady_clock::now().time_since_epoch())
                .count());
      });

      state->set_function("time_humanize", [](const int &timestamp) {
        return utils::chrono::format_timestamp(timestamp);
      });
    }

    sol::object parse_json_object(std::shared_ptr<sol::state_view> state,
                                  nlohmann::json j) {
      switch (j.type()) {
        case nlohmann::json::value_t::null:
          return sol::make_object(*state, sol::lua_nil);
        case nlohmann::json::value_t::string:
          return sol::make_object(*state, j.get<std::string>());
        case nlohmann::json::value_t::number_integer:
          return sol::make_object(*state, j.get<int>());
        case nlohmann::json::value_t::number_unsigned:
          return sol::make_object(*state, j.get<unsigned int>());
        case nlohmann::json::value_t::number_float:
          return sol::make_object(*state, j.get<double>());
        case nlohmann::json::value_t::array: {
          sol::table a = state->create_table();

          for (int i = 0; i < j.size(); ++i) {
            a[i] = parse_json_object(state, j[i]);
          }

          return sol::make_object(*state, a);
        }
        case nlohmann::json::value_t::object: {
          sol::table o = state->create_table();

          for (const auto &[k, v] : j.items()) {
            o[k] = parse_json_object(state, v);
          }

          return sol::make_object(*state, o);
        }
        default:
          throw std::runtime_error("Unsupported Lua type: " +
                                   std::string(j.type_name()));
      }
    }

    nlohmann::json lua_to_json(sol::object o) {
      switch (o.get_type()) {
        case sol::type::lua_nil:
          return nullptr;
        case sol::type::string:
          return o.as<std::string>();
        case sol::type::boolean:
          return o.as<bool>();
        case sol::type::number: {
          double num = o.as<double>();
          if (std::floor(num) == num) {
            return static_cast<long long>(num);
          }
          return num;
        }
        case sol::type::table: {
          sol::table t = o;

          bool is_array = true;
          int count = 0;
          for (auto &kv : t) {
            sol::object key = kv.first;
            if (key.get_type() != sol::type::number) {
              is_array = false;
              break;
            }
            ++count;
          }

          if (is_array) {
            nlohmann::json a = nlohmann::json::array();
            for (size_t i = 1; i <= count; ++i) {
              a.push_back(lua_to_json(t[i]));
            }
            return a;
          } else {
            nlohmann::json ob = nlohmann::json::object();
            for (auto &kv : t) {
              std::string key = kv.first.as<std::string>();
              ob[key] = lua_to_json(kv.second);
            }
            return ob;
          }
        }
        default:
          throw std::runtime_error(
              "Unsupported Lua object for JSON conversion");
      }
    }

    void add_json_library(std::shared_ptr<sol::state> state) {
      state->set_function("json_parse", [state](const std::string &s) {
        nlohmann::json j = nlohmann::json::parse(s);
        return parse_json_object(state, j);
      });

      state->set_function("json_stringify", [](const sol::object &o) {
        return lua_to_json(o).dump();
      });
    }

    void add_base_libraries(std::shared_ptr<sol::state> state) {
      add_bot_library(state);
      add_time_library(state);
      add_json_library(state);
    }

    void add_twitch_library(std::shared_ptr<sol::state> state,
                            const Request &request,
                            const InstanceBundle &bundle) {
      // TODO: ratelimits
      state->set_function("twitch_get_chatters", [state, &request, &bundle]() {
        auto chatters = bundle.helix_client.get_chatters(
            request.channel.get_alias_id(), bundle.irc_client.get_bot_id());

        sol::table o = state->create_table();

        std::for_each(chatters.begin(), chatters.end(),
                      [state, &o](const api::twitch::schemas::User &x) {
                        sol::table u = state->create_table();

                        u["id"] = x.id;
                        u["login"] = x.login;

                        o.add(u);
                      });

        return o;
      });
    }
  }

  std::string parse_lua_response(const sol::table &r, sol::object &res) {
    if (res.get_type() == sol::type::function) {
      sol::function f = res.as<sol::function>();
      sol::object o = f(r);
      return parse_lua_response(r, o);
    } else if (res.get_type() == sol::type::string) {
      return {"🌑 " + res.as<std::string>()};
    } else if (res.get_type() == sol::type::number) {
      return {"🌑 " + std::to_string(res.as<double>())};
    } else if (res.get_type() == sol::type::boolean) {
      return {"🌑 " + std::to_string(res.as<bool>())};
    } else {
      // should it be ResponseException?
      return "Empty or unsupported response";
    }
  }

  command::Response run_safe_lua_script(const Request &request,
                                        const InstanceBundle &bundle,
                                        const std::string &script) {
    // shared_ptr is unnecessary here, but my library needs it.
    std::shared_ptr<sol::state> state = std::make_shared<sol::state>();

    state->open_libraries(sol::lib::base, sol::lib::table, sol::lib::string);
    library::add_base_libraries(state);

    sol::load_result s = state->load("return " + script);
    if (!s.valid()) {
      s = state->load(script);
    }

    if (!s.valid()) {
      sol::error err = s;
      throw ResponseException<ResponseError::LUA_EXECUTION_ERROR>(
          request, bundle.localization, std::string(err.what()));
    }

    sol::protected_function_result res = s();

    if (!res.valid()) {
      sol::error err = s;
      throw ResponseException<ResponseError::LUA_EXECUTION_ERROR>(
          request, bundle.localization, std::string(err.what()));
    }

    sol::object o = res;

    return parse_lua_response(request.as_lua_table(state), o);
  }

  LuaCommand::LuaCommand(std::shared_ptr<sol::state> luaState,
                         const std::string &script) {
    this->luaState = luaState;

    sol::table data = luaState->script(script);
    this->name = data["name"];
    this->delay = data["delay_sec"];

    sol::table subcommands = data["subcommands"];
    for (auto &k : subcommands) {
      sol::object value = k.second;
      if (value.is<std::string>()) {
        this->subcommands.push_back(value.as<std::string>());
      }
    }

    std::string rights_text = data["minimal_rights"];
    if (rights_text == "suspended") {
      this->level = schemas::PermissionLevel::SUSPENDED;
    } else if (rights_text == "user") {
      this->level = schemas::PermissionLevel::USER;
    } else if (rights_text == "vip") {
      this->level = schemas::PermissionLevel::VIP;
    } else if (rights_text == "moderator") {
      this->level = schemas::PermissionLevel::MODERATOR;
    } else if (rights_text == "broadcaster") {
      this->level = schemas::PermissionLevel::BROADCASTER;
    } else {
      this->level = schemas::PermissionLevel::USER;
    }

    this->handle = data["handle"];
  }

  Response LuaCommand::run(const InstanceBundle &bundle,
                           const Request &request) const {
    sol::object response = this->handle(request.as_lua_table(this->luaState));

    if (response.is<std::string>()) {
      return {response.as<std::string>()};
    } else if (response.is<sol::table>()) {
      sol::table tbl = response.as<sol::table>();
      std::vector<std::string> items;

      for (auto &kv : tbl) {
        sol::object value = kv.second;
        if (value.is<std::string>()) {
          items.push_back(value.as<std::string>());
        }
      }

      return items;
    }

    return {};
  }
}