summaryrefslogtreecommitdiff
path: root/bot/src/modules/lua.hpp
blob: 1f4b665559f7beb7def5fb45064ac2619518125f (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
#pragma once

#include <algorithm>
#include <optional>
#include <string>
#include <vector>

#include "bundle.hpp"
#include "commands/command.hpp"
#include "commands/lua.hpp"
#include "commands/response_error.hpp"
#include "cpr/api.h"
#include "utils/string.hpp"

namespace bot::mod {
  class LuaExecution : public command::Command {
      std::string get_name() const override { return "lua"; }

      int get_delay_seconds() const override { return 1; }

      command::Response run(const InstanceBundle &bundle,
                            const command::Request &request) const override {
        if (!request.message.has_value()) {
          throw ResponseException<ResponseError::NOT_ENOUGH_ARGUMENTS>(
              request, bundle.localization, command::CommandArgument::VALUE);
        }

        std::string script = request.message.value();

        return command::lua::run_safe_lua_script(request, bundle, script);
      }
  };

  class LuaRemoteExecution : public command::Command {
      std::string get_name() const override { return "luaimport"; }

      int get_delay_seconds() const override { return 2; }

      command::Response run(const InstanceBundle &bundle,
                            const command::Request &request) const override {
        if (!request.message.has_value()) {
          throw ResponseException<ResponseError::NOT_ENOUGH_ARGUMENTS>(
              request, bundle.localization, command::CommandArgument::VALUE);
        }

        std::string url = request.message.value();

        std::vector<std::string> mimeTypes = {"text/plain", "text/x-lua"};

        cpr::Response response = cpr::Get(
            cpr::Url{url},
            cpr::Header{{"Accept", utils::string::join_vector(mimeTypes, ',')},
                        {"User-Agent", "https://github.com/ilotterytea/bot"}});

        if (response.status_code != 200) {
          throw ResponseException<ResponseError::EXTERNAL_API_ERROR>(
              request, bundle.localization, response.status_code);
        }

        std::string contentType = response.header["Content-Type"];
        if (!std::any_of(
                mimeTypes.begin(), mimeTypes.end(),
                [&contentType](const auto &x) { return x == contentType; })) {
          throw ResponseException<ResponseError::INCORRECT_ARGUMENT>(
              request, bundle.localization, url);
        }

        std::string script = response.text;

        return command::lua::run_safe_lua_script(request, bundle, script);
      }
  };
}