summary refs log tree commit diff stats
path: root/server_main.cpp
blob: 8da6477ecd1d08febfbf303658c1105206532fcd (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
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
#define ASIO_STANDALONE

#include <base64.hpp>
#include <chrono>
#include <fstream>
#include <functional>
#include <json.hpp>
#include <mutex>
#include <random>
#include <thread>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

#include "cardset.h"
#include "database.h"
#include "imagestore.h"
#include "wizard.h"

namespace {

using socket_type = websocketpp::server<websocketpp::config::asio>;

class server {
 public:
  server(const cardset& cards, const imagestore& images, std::mt19937& rng)
      : cards_(cards), images_(images), rng_(rng) {
    socket_.init_asio();

    socket_.set_message_handler([this](websocketpp::connection_hdl connection,
                                       socket_type::message_ptr message) {
      on_message(connection, message);
    });
  }

  void run() {
    socket_.listen(9002);
    socket_.start_accept();

    asio::post(std::bind(&server::cleanup_thread, this));

    socket_.run();
  }

 private:
  void on_message(websocketpp::connection_hdl connection,
                  socket_type::message_ptr message) {
    nlohmann::json msgJson;

    try {
      msgJson = nlohmann::json::parse(message->get_payload());
    } catch (const std::exception& ex) {
      std::string response = R"(
        {
          "type": "error",
          "msg": "Could not parse message."
        }
      )";

      socket_.send(connection, response,
                   websocketpp::frame::opcode::value::TEXT);
      return;
    }

    std::string cmd = msgJson["cmd"];
    if (cmd == "generate") {
      cmd_generate(connection, msgJson["text"]);
    } else if (cmd == "check") {
      cmd_check(connection, msgJson["token"]);
    } else {
      std::string response = R"(
        {
          "type": "error",
          "msg": "No command in message."
        }
      )";

      socket_.send(connection, response,
                   websocketpp::frame::opcode::value::TEXT);
      return;
    }
  }

  void cmd_generate(websocketpp::connection_hdl connection, std::string text) {
    std::string token;

    {
      std::lock_guard rng_guard(rng_mutex_);
      token = database_.create(rng_);
    }

    nlohmann::json tokenMsg;
    tokenMsg["type"] = "token";
    tokenMsg["token"] = token;
    socket_.send(connection, tokenMsg.dump(),
                 websocketpp::frame::opcode::value::TEXT);

    database_.subscribe(token, [this, connection](const std::string& msg) {
      socket_.send(connection, msg, websocketpp::frame::opcode::value::TEXT);
    });

    asio::post(std::bind(&server::generate_thread, this, token, text));
  }

  void cmd_check(websocketpp::connection_hdl connection, std::string token) {
    bool failed = false;

    try {
      database_.subscribe(token, [this, connection](const std::string& msg) {
        socket_.send(connection, msg, websocketpp::frame::opcode::value::TEXT);
      });

      if (!database_.is_done(token)) {
        return;
      }

      std::string result = database_.getResult(token);
      nlohmann::json resultMsg;
      if (result.empty()) {
        resultMsg["type"] = "error";
        resultMsg["msg"] = "Unknown error occurred.";
      } else {
        resultMsg["type"] = "result";
        resultMsg["image"] = database_.getResult(token);
        resultMsg["msg"] = "Success!";
      }

      socket_.send(connection, resultMsg.dump(),
                   websocketpp::frame::opcode::value::TEXT);
    } catch (const std::exception& ex) {
      failed = true;
    }

    if (failed) {
      try {
        socket_.send(connection, R"(
          {
            "type": "error",
            "msg": "Error retrieving request."
          })",
                     websocketpp::frame::opcode::value::TEXT);
      } catch (const std::exception& ex) {
        // Well, okay
        std::cout << ex.what() << std::endl;
      }
    }
  }

  void generate_thread(std::string token, std::string text) {
    std::unique_ptr<wizard> generator;

    {
      std::lock_guard rng_guard(rng_mutex_);
      generator = std::make_unique<wizard>(cards_, images_, text, rng_);
    }

    try {
      generator->set_status_callback([this, token](const std::string& status) {
        nlohmann::json msg;
        msg["type"] = "status";
        msg["msg"] = status;

        database_.post(token, msg.dump());
      });

      Magick::Image resultImage = generator->run();
      Magick::Blob resultBlob;
      resultImage.write(&resultBlob);

      std::string resultBytes((const char*)resultBlob.data(),
                              resultBlob.length());
      std::string resultEncoded = base64::to_base64(resultBytes);

      database_.setResult(token, resultEncoded);

      nlohmann::json resultMsg;
      resultMsg["type"] = "result";
      resultMsg["image"] = resultEncoded;
      resultMsg["msg"] = "Success!";

      database_.post(token, resultMsg.dump());
    } catch (const std::exception& ex) {
      nlohmann::json response;
      response["type"] = "error";
      response["msg"] =
          std::string("Error generating card (") + ex.what() + ")";

      database_.post(token, response.dump());
    }

    database_.mark_done(token);
  }

  void cleanup_thread() {
    for (;;) {
      // sleep
    }
  }

  const cardset& cards_;
  const imagestore& images_;

  std::mutex rng_mutex_;
  std::mt19937& rng_;

  socket_type socket_;
  database database_;
};

}  // namespace

int main(int argc, char** argv) {
  Magick::InitializeMagick(nullptr);

  std::random_device randomDevice;
  std::mt19937 rng(5);  // randomDevice());

  if (argc != 2) {
    std::cout << "usage: wizard_server [configfile]" << std::endl;
    return -1;
  }

  std::ifstream config_file(argv[1]);
  nlohmann::json config_data = nlohmann::json::parse(config_file);

  cardset cards(config_data["cards_path"]);
  imagestore images(config_data["cache_path"]);

  server app(cards, images, rng);
  app.run();
}