diff --git a/src/ssb.db.c b/src/ssb.db.c index 19d2bc8a..36039548 100644 --- a/src/ssb.db.c +++ b/src/ssb.db.c @@ -2148,6 +2148,33 @@ const char* tf_ssb_db_get_profile_name(sqlite3* db, const char* id) return result; } +static void _tf_ssb_db_invite_cleanup(sqlite3* db) +{ + sqlite3_stmt* statement; + if (sqlite3_prepare(db, "DELETE FROM invites WHERE use_count = 0 OR expires < ?", -1, &statement, NULL) == SQLITE_OK) + { + if (sqlite3_bind_int64(statement, 1, (int64_t)time(NULL)) == SQLITE_OK) + { + if (sqlite3_step(statement) == SQLITE_DONE) + { + if (sqlite3_changes(db)) + { + tf_printf("Cleaned up %d used/expired invites.\n", sqlite3_changes(db)); + } + } + else + { + tf_printf("Invite cleanup failed: %s\n", sqlite3_errmsg(db)); + } + } + sqlite3_finalize(statement); + } + else + { + tf_printf("prepare failed: %s\n", sqlite3_errmsg(db)); + } +} + bool tf_ssb_db_generate_invite(sqlite3* db, const char* id, const char* host, int port, int use_count, int expires_seconds, char* out_invite, size_t size) { if (use_count < -1 || use_count == 0) @@ -2180,6 +2207,8 @@ bool tf_ssb_db_generate_invite(sqlite3* db, const char* id, const char* host, in sqlite3_finalize(statement); } + _tf_ssb_db_invite_cleanup(db); + snprintf(out_invite, size, "%s:%d:%s~%s", host, port, id, seed_b64); return inserted; } @@ -2188,7 +2217,7 @@ bool tf_ssb_db_use_invite(sqlite3* db, const char* id) { bool used = false; sqlite3_stmt* statement; - if (sqlite3_prepare(db, "UPDATE invites SET use_count = use_count - 1 WHERE invite_public_key = ? AND expires > ? AND (use_count > 0 OR use_count = -1)", -1, &statement, + if (sqlite3_prepare(db, "UPDATE invites SET use_count = use_count - 1 WHERE invite_public_key = ? AND expires >= ? AND (use_count > 0 OR use_count = -1)", -1, &statement, NULL) == SQLITE_OK) { if (sqlite3_bind_text(statement, 1, id, -1, NULL) == SQLITE_OK && sqlite3_bind_int64(statement, 2, (int64_t)time(NULL)) == SQLITE_OK) @@ -2197,5 +2226,8 @@ bool tf_ssb_db_use_invite(sqlite3* db, const char* id) } sqlite3_finalize(statement); } + + _tf_ssb_db_invite_cleanup(db); + return used; }