summaryrefslogtreecommitdiff
path: root/2026/games_submissions/just__jane/src/score.cpp
blob: ea0aa78bf02a4a1fd4f8df2d7efdcbacc17d4a97 (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
#include <cstring>
#include <format>
#include <string>

#include <emscripten/em_types.h>
#include <emscripten/emscripten.h>
#include <emscripten/fetch.h>
#include <emscripten/html5.h>

struct PostData {
  char *body;
};

EM_JS(char *, get_cookie, (const char *name), {
  const cookieName = UTF8ToString(name) + "=";
  const cookies = document.cookie.split(";");

  for (let c of cookies) {
    c = c.trim();

    if (c.startsWith(cookieName)) {
      const value = c.substring(cookieName.length);
      const len = lengthBytesUTF8(value) + 1;
      const buffer = _malloc(len);
      stringToUTF8(value, buffer, len);
      return buffer;
    }
  }

  return 0;
});

void cleanup(emscripten_fetch_t *fetch) {
  auto *data = static_cast<PostData *>(fetch->userData);
  free(data->body);
  delete data;
  emscripten_fetch_close(fetch);
}

void on_success(emscripten_fetch_t *fetch) {
  printf("success: %d\n", fetch->status);
  cleanup(fetch);
}

void on_error(emscripten_fetch_t *fetch) {
  printf("error: %d\n", fetch->status);
  cleanup(fetch);
}

void post_score(int score) {
  auto username = get_cookie("bahms_user_login");
  if (!username) {
    return;
  }

  std::string text = std::format("## {}\nscore: {}", username, score);

  auto *data = new PostData;
  data->body = static_cast<char *>(malloc(text.size()));
  memcpy(data->body, text.data(), text.size());

  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);

  strcpy(attr.requestMethod, "POST");
  attr.withCredentials = true;

  const char *headers[] = {"Content-Type", "text/plain; charset=utf-8", nullptr};

  attr.requestHeaders = headers;
  attr.requestData = data->body;
  attr.requestDataSize = text.size();
  attr.userData = data;

  attr.onsuccess = on_success;
  attr.onerror = on_error;

  emscripten_fetch(&attr, "https://api.bahms.org/v1/game/sakura-samurai");
}