nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
guilds.cc
Go to the documentation of this file.
1#include "server/guilds.h"
2
3#include <algorithm>
4#include <chrono>
5#include <cstddef>
6#include <cstdint>
7#include <string>
8#include <string_view>
9#include <utility>
10#include <vector>
11
12#include "absl/strings/ascii.h"
13#include "absl/strings/numbers.h"
14#include "absl/strings/str_cat.h"
15#include "protocol/messages.h"
16#include "server/levels.h"
17
18namespace nanommo {
19
20namespace {
21
22// Each player has one invitation at a time, by their character's id, which
23// holds the guild's.
24std::string InvitationOf(uint32_t player) {
25 return absl::StrCat("guild_invite:", player);
26}
27
28// A guild's ask to war another, by both their ids, which holds who asked.
29std::string WarAskOf(const std::string& world, uint32_t guild, uint32_t enemy) {
30 return absl::StrCat("war_ask:", world, ":", guild, ":", enemy);
31}
32
33// A FailedPrecondition error, in words for the leader of ours, when either
34// guild is in a war that hasn't ended, as a guild is in one at a time.
35absl::Status NeitherAtWar(Database& database, uint32_t ours, uint32_t theirs,
36 std::string_view their_name) {
37 const std::string a = absl::StrCat(ours);
38 const std::string b = absl::StrCat(theirs);
39 const absl::StatusOr<Result> wars = database.Run(
40 "SELECT challenger, challenged FROM guild_wars WHERE ends_at > NOW() "
41 "AND (challenger IN (?, ?) OR challenged IN (?, ?))",
42 {a, b, a, b});
43 if (!wars.ok()) {
44 return wars.status();
45 }
46 for (const std::vector<std::string>& war : wars->rows) {
47 if (war[0] == a || war[1] == a) {
48 return Refusal(absl::StatusCode::kFailedPrecondition,
49 Msg("Your guild is at war already."));
50 }
51 }
52 if (!wars->rows.empty()) {
53 return Refusal(absl::StatusCode::kFailedPrecondition,
54 Msg("$0 is at war already.", Name(their_name)));
55 }
56 return absl::OkStatus();
57}
58
59// A FailedPrecondition refusal, in the words given, while the guild is in a
60// war that hasn't ended. Nobody leaves a war: a losing side could dodge it, or
61// disband, which takes the war's kills with the guild. The caller has the
62// guild's row locked, as a war's yes locks it, so no war starts meanwhile.
63absl::Status NotAtWar(Database& database, uint32_t guild, const Sentence& why) {
64 const std::string id = absl::StrCat(guild);
65 const absl::StatusOr<Result> wars = database.Run(
66 "SELECT id FROM guild_wars WHERE ends_at > NOW() "
67 "AND (challenger = ? OR challenged = ?)",
68 {id, id});
69 if (!wars.ok()) {
70 return wars.status();
71 }
72 if (!wars->rows.empty()) {
73 return Refusal(absl::StatusCode::kFailedPrecondition, why);
74 }
75 return absl::OkStatus();
76}
77
78// A member's rank in the guild, with their row locked, or NotFound when they
79// aren't in it.
80absl::StatusOr<protocol::Rank> RankIn(Database& database, uint32_t guild,
81 uint32_t player) {
82 const absl::StatusOr<Result> member = database.Run(
83 "SELECT grade FROM guild_members WHERE player = ? AND guild = ? "
84 "FOR UPDATE",
85 {absl::StrCat(player), absl::StrCat(guild)});
86 if (!member.ok()) {
87 return member.status();
88 }
89 int grade = 0;
90 if (member->rows.empty()) {
91 return Refusal(absl::StatusCode::kNotFound,
92 Msg("They're not in your guild."));
93 }
94 if (!absl::SimpleAtoi(member->rows.front()[0], &grade) ||
95 !protocol::Rank_IsValid(grade)) {
96 return absl::InternalError("a grade that isn't a rank");
97 }
98 return static_cast<protocol::Rank>(grade);
99}
100
101// The guild of a player who's changing something in it, in a transaction:
102// its row locked first, as every change to a guild locks it, so changes to
103// one guild happen one at a time, then the player's own, which someone may
104// have changed before we got the guild's.
105absl::StatusOr<Membership> LockFor(Database& database, uint32_t player) {
106 Membership membership;
107 const absl::StatusOr<Result> in =
108 database.Run("SELECT guild FROM guild_members WHERE player = ?",
109 {absl::StrCat(player)});
110 if (!in.ok()) {
111 return in.status();
112 }
113 if (in->rows.empty() ||
114 !absl::SimpleAtoi(in->rows.front()[0], &membership.guild)) {
115 return Refusal(absl::StatusCode::kNotFound, Msg("You're in no guild."));
116 }
117 const absl::StatusOr<Result> guild =
118 database.Run("SELECT name FROM guilds WHERE id = ? FOR UPDATE",
119 {absl::StrCat(membership.guild)});
120 if (!guild.ok()) {
121 return guild.status();
122 }
123 const absl::StatusOr<protocol::Rank> rank =
124 RankIn(database, membership.guild, player);
125 if (guild->rows.empty() || absl::IsNotFound(rank.status())) {
126 return Refusal(absl::StatusCode::kNotFound, Msg("You're in no guild."));
127 }
128 if (!rank.ok()) {
129 return rank.status();
130 }
131 membership.name = guild->rows.front()[0];
132 membership.rank = *rank;
133 return membership;
134}
135
136} // namespace
137
138absl::Status CheckGuildName(std::string_view name) {
139 if (name.size() < 3 || name.size() > 24) {
140 return Refusal(absl::StatusCode::kInvalidArgument,
141 Msg("Guild names are 3 to 24 characters long."));
142 }
143 // Words of letters, one space apart, so a name starts and ends with a
144 // letter, and two names can't differ by their spaces alone.
145 for (size_t i = 0; i < name.size(); ++i) {
146 const bool between_words =
147 name[i] == ' ' && i > 0 && i + 1 < name.size() && name[i - 1] != ' ';
148 if (!absl::ascii_isalpha(static_cast<unsigned char>(name[i])) &&
149 !between_words) {
150 return Refusal(
151 absl::StatusCode::kInvalidArgument,
152 Msg("Guild names are letters, with one space between words."));
153 }
154 }
155 return absl::OkStatus();
156}
157
158absl::StatusOr<Membership> Guilds::Of(uint32_t player) {
159 const absl::StatusOr<Result> rows = database_.Run(
160 "SELECT guilds.id, guilds.name, guild_members.grade "
161 "FROM guild_members JOIN guilds ON guilds.id = guild_members.guild "
162 "WHERE guild_members.player = ?",
163 {absl::StrCat(player)});
164 if (!rows.ok()) {
165 return rows.status();
166 }
167 if (rows->rows.empty()) {
168 return Refusal(absl::StatusCode::kNotFound, Msg("You're in no guild."));
169 }
170 const std::vector<std::string>& row = rows->rows.front();
171 Membership membership;
172 int grade = 0;
173 if (!absl::SimpleAtoi(row[0], &membership.guild) ||
174 !absl::SimpleAtoi(row[2], &grade) || !protocol::Rank_IsValid(grade)) {
175 return absl::InternalError("a guild member that isn't numbers");
176 }
177 membership.name = row[1];
178 membership.rank = static_cast<protocol::Rank>(grade);
179 return membership;
180}
181
182absl::StatusOr<Membership> Guilds::Create(const std::string& world,
183 uint32_t player,
184 const std::string& name) {
185 if (const absl::Status checked = CheckGuildName(name); !checked.ok()) {
186 return checked;
187 }
188 Membership membership{.name = name, .rank = protocol::RANK_LEADER};
189 // The guild and its leader go in together, so when the character is in a
190 // guild already, the new guild goes too, and its name stays free.
191 const absl::Status created = database_.Transaction([&]() -> absl::Status {
192 const absl::StatusOr<Result> guild = database_.Run(
193 "INSERT INTO guilds (world, name) VALUES (?, ?)", {world, name});
194 if (absl::IsAlreadyExists(guild.status())) {
195 return Refusal(
196 absl::StatusCode::kAlreadyExists,
197 Msg("There's a guild called that in $0 already.", Name(world)));
198 }
199 if (!guild.ok()) {
200 return guild.status();
201 }
202 membership.guild = static_cast<uint32_t>(guild->insert_id);
203 const absl::StatusOr<Result> leader = database_.Run(
204 "INSERT INTO guild_members (player, guild, grade) VALUES (?, ?, ?)",
205 {absl::StrCat(player), absl::StrCat(membership.guild),
206 absl::StrCat(static_cast<int>(protocol::RANK_LEADER))});
207 if (absl::IsAlreadyExists(leader.status())) {
208 return Refusal(absl::StatusCode::kAlreadyExists,
209 Msg("You're in a guild already."));
210 }
211 return leader.status();
212 });
213 if (!created.ok()) {
214 return created;
215 }
216 return membership;
217}
218
219absl::StatusOr<Membership> Guilds::Invite(uint32_t from, uint32_t player) {
220 absl::StatusOr<Membership> asking = Of(from);
221 if (!asking.ok()) {
222 return asking.status();
223 }
224 if (asking->rank == protocol::RANK_MEMBER) {
225 return Refusal(absl::StatusCode::kPermissionDenied,
226 Msg("Only officers and the leader can ask someone in."));
227 }
228 // NX sets it only when there's none, so of two asking at once, from any
229 // instance, one does, and the invitation runs out by itself.
230 const absl::StatusOr<std::string> asked =
231 redis_.Command({"SET", InvitationOf(player), absl::StrCat(asking->guild),
232 "EX", absl::StrCat(kInvitationLife.count()), "NX"});
233 if (absl::IsNotFound(asked.status())) {
234 return Refusal(absl::StatusCode::kAlreadyExists,
235 Msg("They've been asked to join a guild."));
236 }
237 if (!asked.ok()) {
238 return asked.status();
239 }
240 return asking;
241}
242
243absl::StatusOr<Membership> Guilds::Accept(uint32_t player) {
244 // Read, and not taken yet, so that a MySQL that fails for a moment leaves
245 // it to try again. Two at once can't both join, as a character is in one
246 // guild at most.
247 const absl::StatusOr<std::string> invitation =
248 redis_.Command({"GET", InvitationOf(player)});
249 if (absl::IsNotFound(invitation.status())) {
250 return Refusal(absl::StatusCode::kNotFound,
251 Msg("Nobody's asked you, or it's run out."));
252 }
253 if (!invitation.ok()) {
254 return invitation.status();
255 }
256 Membership membership;
257 if (!absl::SimpleAtoi(*invitation, &membership.guild)) {
258 return absl::InternalError("an invitation that isn't a number");
259 }
260 const absl::Status joined = database_.Transaction([&]() -> absl::Status {
261 // Locking the guild's row first, as every change to a guild does, so
262 // that changes to one guild happen one at a time, and it can't end or
263 // fill up while we join.
264 const absl::StatusOr<Result> guild =
265 database_.Run("SELECT name FROM guilds WHERE id = ? FOR UPDATE",
266 {absl::StrCat(membership.guild)});
267 if (!guild.ok()) {
268 return guild.status();
269 }
270 if (guild->rows.empty()) {
271 return Refusal(absl::StatusCode::kNotFound, Msg("That guild is gone."));
272 }
273 membership.name = guild->rows.front()[0];
274 const absl::StatusOr<Result> members =
275 database_.Run("SELECT COUNT(*) FROM guild_members WHERE guild = ?",
276 {absl::StrCat(membership.guild)});
277 if (!members.ok()) {
278 return members.status();
279 }
280 int count = 0;
281 if (!absl::SimpleAtoi(members->rows.front()[0], &count)) {
282 return absl::InternalError("a count that isn't a number");
283 }
284 if (count >= kMostMembers) {
285 return Refusal(absl::StatusCode::kResourceExhausted,
286 Msg("$0 is full.", Name(membership.name)));
287 }
288 const absl::StatusOr<Result> member =
289 database_.Run("INSERT INTO guild_members (player, guild) VALUES (?, ?)",
290 {absl::StrCat(player), absl::StrCat(membership.guild)});
291 if (absl::IsAlreadyExists(member.status())) {
292 return Refusal(absl::StatusCode::kAlreadyExists,
293 Msg("You're in a guild already."));
294 }
295 return member.status();
296 });
297 // Joined, or never will be with this one, it's spent. If deleting it fails,
298 // it runs out by itself.
299 if (!absl::IsAborted(joined) && !absl::IsUnavailable(joined)) {
300 redis_.Command({"DEL", InvitationOf(player)}).status().IgnoreError();
301 }
302 if (!joined.ok()) {
303 return joined;
304 }
305 return membership;
306}
307
308absl::StatusOr<Changed> Guilds::SetRank(uint32_t from, uint32_t player,
309 protocol::Rank rank) {
310 if (rank == protocol::RANK_LEADER || from == player) {
311 return Refusal(
312 absl::StatusCode::kInvalidArgument,
313 Msg("The leader makes members officers, and officers members."));
314 }
315 Changed changed;
316 const absl::Status done = database_.Transaction([&]() -> absl::Status {
317 const absl::StatusOr<Membership> leading = LockFor(database_, from);
318 if (!leading.ok()) {
319 return leading.status();
320 }
321 if (leading->rank != protocol::RANK_LEADER) {
322 return Refusal(absl::StatusCode::kPermissionDenied,
323 Msg("Only the leader changes ranks."));
324 }
325 changed.guild = leading->guild;
326 changed.guild_name = leading->name;
327 const absl::StatusOr<protocol::Rank> now =
328 RankIn(database_, leading->guild, player);
329 if (!now.ok()) {
330 return now.status();
331 }
332 const absl::StatusOr<Result> named = database_.Run(
333 "SELECT name FROM players WHERE id = ?", {absl::StrCat(player)});
334 if (!named.ok()) {
335 return named.status();
336 }
337 changed.player_name = named->rows.empty() ? "" : named->rows.front()[0];
338 return database_
339 .Run("UPDATE guild_members SET grade = ? WHERE player = ?",
340 {absl::StrCat(static_cast<int>(rank)), absl::StrCat(player)})
341 .status();
342 });
343 if (!done.ok()) {
344 return done;
345 }
346 return changed;
347}
348
349absl::StatusOr<Changed> Guilds::Kick(uint32_t from, uint32_t player) {
350 if (from == player) {
351 return Refusal(absl::StatusCode::kInvalidArgument,
352 Msg("To go, leave the guild."));
353 }
354 Changed changed;
355 const absl::Status done = database_.Transaction([&]() -> absl::Status {
356 const absl::StatusOr<Membership> acting = LockFor(database_, from);
357 if (!acting.ok()) {
358 return acting.status();
359 }
360 const absl::StatusOr<protocol::Rank> theirs =
361 RankIn(database_, acting->guild, player);
362 if (!theirs.ok()) {
363 return theirs.status();
364 }
365 if (acting->rank <= *theirs) {
366 return Refusal(absl::StatusCode::kPermissionDenied,
367 Msg("The leader removes officers and members, and "
368 "officers members."));
369 }
370 if (const absl::Status free = NotAtWar(
371 database_, acting->guild,
372 Msg("Nobody's removed from a guild at war until the war's over."));
373 !free.ok()) {
374 return free;
375 }
376 changed.guild = acting->guild;
377 changed.guild_name = acting->name;
378 const absl::StatusOr<Result> named = database_.Run(
379 "SELECT name FROM players WHERE id = ?", {absl::StrCat(player)});
380 if (!named.ok()) {
381 return named.status();
382 }
383 changed.player_name = named->rows.empty() ? "" : named->rows.front()[0];
384 return database_
385 .Run("DELETE FROM guild_members WHERE player = ?",
386 {absl::StrCat(player)})
387 .status();
388 });
389 if (!done.ok()) {
390 return done;
391 }
392 return changed;
393}
394
395absl::StatusOr<Membership> Guilds::Disband(uint32_t from) {
396 Membership ended;
397 const absl::Status done = database_.Transaction([&]() -> absl::Status {
398 const absl::StatusOr<Membership> leading = LockFor(database_, from);
399 if (!leading.ok()) {
400 return leading.status();
401 }
402 if (leading->rank != protocol::RANK_LEADER) {
403 return Refusal(absl::StatusCode::kPermissionDenied,
404 Msg("Only the leader disbands the guild."));
405 }
406 if (const absl::Status free =
407 NotAtWar(database_, leading->guild,
408 Msg("A guild at war can't be disbanded until the war's "
409 "over."));
410 !free.ok()) {
411 return free;
412 }
413 ended = *leading;
414 // Its members' rows go with it.
415 return database_
416 .Run("DELETE FROM guilds WHERE id = ?", {absl::StrCat(ended.guild)})
417 .status();
418 });
419 if (!done.ok()) {
420 return done;
421 }
422 return ended;
423}
424
425absl::StatusOr<std::vector<protocol::GuildMember>> Guilds::Roster(
426 uint32_t guild) {
427 const absl::StatusOr<Result> rows = database_.Run(
428 "SELECT guild_members.player, players.name, guild_members.grade, "
429 "players.experience FROM guild_members "
430 "JOIN players ON players.id = guild_members.player "
431 "WHERE guild_members.guild = ? "
432 "ORDER BY guild_members.grade DESC, players.name",
433 {absl::StrCat(guild)});
434 if (!rows.ok()) {
435 return rows.status();
436 }
437 std::vector<protocol::GuildMember> roster;
438 roster.reserve(rows->rows.size());
439 for (const std::vector<std::string>& row : rows->rows) {
440 uint32_t id = 0;
441 int grade = 0;
442 uint32_t experience = 0;
443 if (!absl::SimpleAtoi(row[0], &id) || !absl::SimpleAtoi(row[2], &grade) ||
444 !absl::SimpleAtoi(row[3], &experience) ||
445 !protocol::Rank_IsValid(grade)) {
446 return absl::InternalError("a guild member that isn't numbers");
447 }
448 protocol::GuildMember& member = roster.emplace_back();
449 member.set_id(id);
450 member.set_name(row[1]);
451 member.set_rank(static_cast<protocol::Rank>(grade));
452 member.set_level(static_cast<uint32_t>(LevelFor(experience).number));
453 }
454 return roster;
455}
456
457absl::StatusOr<War> Guilds::AskToWar(const std::string& world, uint32_t from,
458 const std::string& name) {
459 const absl::StatusOr<Membership> asking = Of(from);
460 if (!asking.ok()) {
461 return asking.status();
462 }
463 if (asking->rank != protocol::RANK_LEADER) {
464 return Refusal(absl::StatusCode::kPermissionDenied,
465 Msg("Only the leader takes the guild to war."));
466 }
467 // MySQL compares the name without its case.
468 const absl::StatusOr<Result> found =
469 database_.Run("SELECT id, name FROM guilds WHERE world = ? AND name = ?",
470 {world, name});
471 if (!found.ok()) {
472 return found.status();
473 }
474 if (found->rows.empty()) {
475 return Refusal(
476 absl::StatusCode::kNotFound,
477 Msg("There's no guild called $0 in $1.", Name(name), Name(world)));
478 }
479 War war{.challenger = asking->guild, .challenger_name = asking->name};
480 if (!absl::SimpleAtoi(found->rows.front()[0], &war.challenged)) {
481 return absl::InternalError("a guild that isn't a number");
482 }
483 war.challenged_name = found->rows.front()[1];
484 if (war.challenged == war.challenger) {
485 return Refusal(absl::StatusCode::kInvalidArgument,
486 Msg("Your guild can't go to war with itself."));
487 }
488 // Asking back the guild that asked is a yes, as in a duel, and they're the
489 // challenger.
490 const absl::StatusOr<std::string> asked =
491 redis_.Command({"GET", WarAskOf(world, war.challenged, war.challenger)});
492 if (asked.ok()) {
493 std::swap(war.challenger, war.challenged);
494 std::swap(war.challenger_name, war.challenged_name);
495 return StartWar(world, from, std::move(war));
496 }
497 if (!absl::IsNotFound(asked.status())) {
498 return asked.status();
499 }
500 if (const absl::Status free = NeitherAtWar(
501 database_, war.challenger, war.challenged, war.challenged_name);
502 !free.ok()) {
503 return free;
504 }
505 // NX sets it only when there's none, so a guild asks another once until
506 // it's answered, and the ask runs out by itself.
507 const absl::StatusOr<std::string> set = redis_.Command(
508 {"SET", WarAskOf(world, war.challenger, war.challenged),
509 absl::StrCat(from), "EX", absl::StrCat(kWarAskLife.count()), "NX"});
510 if (absl::IsNotFound(set.status())) {
511 return Refusal(absl::StatusCode::kAlreadyExists,
512 Msg("You've asked $0 already.", Name(war.challenged_name)));
513 }
514 if (!set.ok()) {
515 return set.status();
516 }
517 return war;
518}
519
520absl::StatusOr<War> Guilds::StartWar(const std::string& world, uint32_t from,
521 War war) {
522 const absl::Status started = database_.Transaction([&]() -> absl::Status {
523 // Both guilds' rows, the lower id first, before any member's. Two leaders
524 // saying yes at once, each to the other's ask, would otherwise each lock
525 // their own and wait for the other's.
526 for (const uint32_t guild : {std::min(war.challenger, war.challenged),
527 std::max(war.challenger, war.challenged)}) {
528 const absl::StatusOr<Result> locked =
529 database_.Run("SELECT id FROM guilds WHERE id = ? FOR UPDATE",
530 {absl::StrCat(guild)});
531 if (!locked.ok()) {
532 return locked.status();
533 }
534 if (locked->rows.empty()) {
535 return Refusal(absl::StatusCode::kNotFound, Msg("That guild is gone."));
536 }
537 }
538 // They may have stopped leading it since we asked.
539 const absl::StatusOr<protocol::Rank> rank =
540 RankIn(database_, war.challenged, from);
541 if (absl::IsNotFound(rank.status())) {
542 return Refusal(absl::StatusCode::kNotFound, Msg("You're in no guild."));
543 }
544 if (!rank.ok()) {
545 return rank.status();
546 }
547 if (*rank != protocol::RANK_LEADER) {
548 return Refusal(absl::StatusCode::kPermissionDenied,
549 Msg("Only the leader takes the guild to war."));
550 }
551 if (const absl::Status free = NeitherAtWar(
552 database_, war.challenged, war.challenger, war.challenger_name);
553 !free.ok()) {
554 return free;
555 }
556 const absl::StatusOr<Result> inserted = database_.Run(
557 "INSERT INTO guild_wars (world, challenger, challenged, ends_at) "
558 "VALUES (?, ?, ?, NOW() + INTERVAL ? SECOND)",
559 {world, absl::StrCat(war.challenger), absl::StrCat(war.challenged),
560 absl::StrCat(std::chrono::seconds(kWarLength).count())});
561 if (!inserted.ok()) {
562 return inserted.status();
563 }
564 war.id = static_cast<uint32_t>(inserted->insert_id);
565 return absl::OkStatus();
566 });
567 // Started, or never will be from this ask, it's spent. If deleting it fails,
568 // it runs out by itself.
569 if (!absl::IsAborted(started) && !absl::IsUnavailable(started)) {
570 redis_.Command({"DEL", WarAskOf(world, war.challenger, war.challenged)})
571 .status()
572 .IgnoreError();
573 }
574 if (!started.ok()) {
575 return started;
576 }
577 war.left = kWarLength;
578 return war;
579}
580
581absl::StatusOr<std::vector<War>> Guilds::Wars(const std::string& world) {
582 // Each side's score is how many of the war's kills are its, which the key
583 // on the war and the guild counts.
584 const absl::StatusOr<Result> rows = database_.Run(
585 "SELECT guild_wars.id, challenger, asking.name, challenged, asked.name, "
586 "(SELECT COUNT(*) FROM war_kills WHERE war = guild_wars.id "
587 "AND guild = challenger), "
588 "(SELECT COUNT(*) FROM war_kills WHERE war = guild_wars.id "
589 "AND guild = challenged), "
590 "TIMESTAMPDIFF(SECOND, NOW(), ends_at) FROM guild_wars "
591 "JOIN guilds AS asking ON asking.id = guild_wars.challenger "
592 "JOIN guilds AS asked ON asked.id = guild_wars.challenged "
593 "WHERE guild_wars.world = ? AND ends_at > NOW()",
594 {world});
595 if (!rows.ok()) {
596 return rows.status();
597 }
598 std::vector<War> wars;
599 wars.reserve(rows->rows.size());
600 for (const std::vector<std::string>& row : rows->rows) {
601 War& war = wars.emplace_back();
602 int64_t left = 0;
603 if (!absl::SimpleAtoi(row[0], &war.id) ||
604 !absl::SimpleAtoi(row[1], &war.challenger) ||
605 !absl::SimpleAtoi(row[3], &war.challenged) ||
606 !absl::SimpleAtoi(row[5], &war.challenger_kills) ||
607 !absl::SimpleAtoi(row[6], &war.challenged_kills) ||
608 !absl::SimpleAtoi(row[7], &left)) {
609 return absl::InternalError("a war that isn't numbers");
610 }
611 war.challenger_name = row[2];
612 war.challenged_name = row[4];
613 war.left = std::chrono::seconds(left);
614 }
615 return wars;
616}
617
618absl::Status Guilds::Decline(uint32_t player) {
619 return redis_.Command({"DEL", InvitationOf(player)}).status();
620}
621
622absl::StatusOr<Left> Guilds::Leave(uint32_t player) {
623 absl::StatusOr<Left> left;
624 const absl::Status done = database_.Transaction([&]() -> absl::Status {
625 left = LeaveGuild(database_, player);
626 return left.status();
627 });
628 if (!done.ok()) {
629 return done;
630 }
631 return left;
632}
633
634absl::StatusOr<Left> LeaveGuild(Database& database, uint32_t player) {
635 const absl::StatusOr<Membership> leaving = LockFor(database, player);
636 if (!leaving.ok()) {
637 return leaving.status();
638 }
639 if (const absl::Status free =
640 NotAtWar(database, leaving->guild,
641 Msg("Nobody leaves a guild at war until the war's over."));
642 !free.ok()) {
643 return free;
644 }
645 Left left;
646 left.guild = leaving->guild;
647 left.name = leaving->name;
648 const absl::StatusOr<Result> gone = database.Run(
649 "DELETE FROM guild_members WHERE player = ?", {absl::StrCat(player)});
650 if (!gone.ok()) {
651 return gone.status();
652 }
653 if (leaving->rank != protocol::RANK_LEADER) {
654 return left;
655 }
656 // The highest rank left, and of those, who joined first.
657 const absl::StatusOr<Result> next = database.Run(
658 "SELECT guild_members.player, players.name FROM guild_members "
659 "JOIN players ON players.id = guild_members.player "
660 "WHERE guild_members.guild = ? "
661 "ORDER BY guild_members.grade DESC, guild_members.joined_at, "
662 "guild_members.player LIMIT 1 FOR UPDATE",
663 {absl::StrCat(left.guild)});
664 if (!next.ok()) {
665 return next.status();
666 }
667 if (next->rows.empty()) {
668 left.ended = true;
669 const absl::StatusOr<Result> ended = database.Run(
670 "DELETE FROM guilds WHERE id = ?", {absl::StrCat(left.guild)});
671 if (!ended.ok()) {
672 return ended.status();
673 }
674 return left;
675 }
676 if (!absl::SimpleAtoi(next->rows.front()[0], &left.successor)) {
677 return absl::InternalError("a member that isn't a number");
678 }
679 left.successor_name = next->rows.front()[1];
680 const absl::StatusOr<Result> promoted =
681 database.Run("UPDATE guild_members SET grade = ? WHERE player = ?",
682 {absl::StrCat(static_cast<int>(protocol::RANK_LEADER)),
683 absl::StrCat(left.successor)});
684 if (!promoted.ok()) {
685 return promoted.status();
686 }
687 return left;
688}
689
690} // namespace nanommo
absl::Status Transaction(const std::function< absl::Status()> &statements)
Definition database.cc:299
absl::StatusOr< Result > Run(std::string_view sql, const std::vector< std::string > &values={})
Definition database.cc:186
absl::StatusOr< Membership > Of(uint32_t player)
The guild the character is in, or a NotFound error for none.
Definition guilds.cc:158
absl::StatusOr< Membership > Accept(uint32_t player)
Definition guilds.cc:243
static constexpr std::chrono::seconds kWarAskLife
How long a guild's ask to war waits for the other's yes.
Definition guilds.h:71
absl::StatusOr< Membership > Invite(uint32_t from, uint32_t player)
Definition guilds.cc:219
absl::StatusOr< War > AskToWar(const std::string &world, uint32_t from, const std::string &name)
Definition guilds.cc:457
absl::StatusOr< Left > Leave(uint32_t player)
The player leaves their guild, as LeaveGuild says, in a transaction.
Definition guilds.cc:622
static constexpr std::chrono::minutes kWarLength
How long a war lasts, from the yes.
Definition guilds.h:73
absl::StatusOr< Changed > Kick(uint32_t from, uint32_t player)
Definition guilds.cc:349
absl::StatusOr< std::vector< protocol::GuildMember > > Roster(uint32_t guild)
Definition guilds.cc:425
absl::Status Decline(uint32_t player)
The player says no to the guild that asked, so that another can ask.
Definition guilds.cc:618
absl::StatusOr< Changed > SetRank(uint32_t from, uint32_t player, protocol::Rank rank)
Definition guilds.cc:308
absl::StatusOr< std::vector< War > > Wars(const std::string &world)
Definition guilds.cc:581
static constexpr int kMostMembers
How many characters a guild can have.
Definition guilds.h:67
absl::StatusOr< Membership > Create(const std::string &world, uint32_t player, const std::string &name)
Definition guilds.cc:182
absl::StatusOr< Membership > Disband(uint32_t from)
Definition guilds.cc:395
static constexpr std::chrono::seconds kInvitationLife
How long an invitation waits for an answer.
Definition guilds.h:69
Definition chat.cc:9
absl::Status Refusal(absl::StatusCode code, const Sentence &why)
Definition messages.cc:218
Level LevelFor(uint32_t experience)
Definition levels.cc:5
absl::Status CheckGuildName(std::string_view name)
Definition guilds.cc:138
Sentence Msg(std::string_view text, Parts... parts)
Definition messages.h:92
Part Name(std::string_view name)
Definition messages.cc:113
absl::StatusOr< Left > LeaveGuild(Database &database, uint32_t player)
Definition guilds.cc:634
What a change to another member of a guild did, for the news.
Definition guilds.h:43
uint32_t guild
Definition guilds.h:44
std::string guild_name
Definition guilds.h:45
std::string player_name
The member it changed, by their name.
Definition guilds.h:47
What leaving a guild did.
Definition guilds.h:31
bool ended
Whether they were the last one in it, so it's gone.
Definition guilds.h:39
uint32_t successor
Definition guilds.h:36
std::string successor_name
Definition guilds.h:37
uint32_t guild
Definition guilds.h:32
std::string name
Definition guilds.h:33
The guild a character is in, and its rank there.
Definition guilds.h:24
std::string name
Definition guilds.h:26
protocol::Rank rank
Definition guilds.h:27
uint32_t guild
Definition guilds.h:25
uint32_t challenged_kills
Definition wars.h:23
std::string challenged_name
Definition wars.h:21
uint32_t challenger_kills
Definition wars.h:22
std::chrono::seconds left
Definition wars.h:24
uint32_t id
Definition wars.h:17
std::string challenger_name
Definition wars.h:19
uint32_t challenger
Definition wars.h:18
uint32_t challenged
Definition wars.h:20