Cavoke  1.1.0
A Platform for creating and hosting multiplayer turn-based board games
Loading...
Searching...
No Matches
games_storage.cpp
1#include "games_storage.h"
2#include <boost/filesystem.hpp>
3#include <boost/range/iterator_range.hpp>
4#include <iostream>
5#include <string>
6#include <utility>
7
8namespace cavoke::server::model {
9
10GamesStorage::GamesStorage(GamesStorageConfig config)
11 : m_config(std::move(config)) {
12 if (!boost::filesystem::exists(m_config.games_directory)) {
13 bool success =
14 boost::filesystem::create_directories(m_config.games_directory);
15 if (!success) {
16 throw std::invalid_argument("Cannot create games directory " +
17 m_config.games_directory.string() +
18 "\n");
19 }
20 }
21
22 if (!boost::filesystem::is_directory(m_config.games_directory)) {
23 throw std::invalid_argument("Invalid games directory " +
24 m_config.games_directory.string() + "\n");
25 }
26
27 update();
28}
29
30std::vector<Game> GamesStorage::list_games() {
31 update();
32
33 std::vector<Game> result;
34
35 {
36 std::shared_lock lock(m_games_mtx);
37 for (const auto &e : m_games) {
38 // cppcheck-suppress useStlAlgorithm
39 result.emplace_back(e.second);
40 }
41 }
42
43 return result;
44}
45
46void GamesStorage::update() {
47 std::unique_lock lock(m_games_mtx);
48
49 m_games.clear();
50 for (auto &entry : boost::make_iterator_range(
51 boost::filesystem::directory_iterator(m_config.games_directory),
52 {})) {
53 if (!Game::is_game_directory(entry, m_config)) {
54 // TODO: logging
55 std::cerr << entry
56 << " entity from games directory is not a valid game"
57 << std::endl;
58 } else {
59 Game game(entry, m_config);
60 m_games.emplace(game.config.id, game);
61 }
62 }
63}
64
65std::optional<Game> GamesStorage::get_game_by_id(const std::string &game_id) {
66 std::shared_lock lock(m_games_mtx);
67
68 if (m_games.count(game_id) > 0) {
69 return m_games[game_id];
70 }
71 return {};
72}
73
74} // namespace cavoke::server::model