Skip to content

Commit e0204f7

Browse files
Make presence clear async, clean up temp session code
1 parent 05fba68 commit e0204f7

4 files changed

Lines changed: 23 additions & 22 deletions

File tree

src/api/util/utility/EmbedHandlers.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
along with this program. If not, see <https://www.gnu.org/licenses/>.
1717
*/
1818

19-
import { arrayDistinctBy, arrayGroupBy, Config, EmbedCache, emitEvent, Message, MessageUpdateEvent, normalizeUrl, OrmUtils } from "@spacebar/util";
19+
import { arrayDistinctBy, arrayGroupBy, Config, EmbedCache, emitEvent, Message, MessageUpdateEvent, normalizeUrl, OrmUtils, sleep } from "@spacebar/util";
2020
import { Embed, EmbedImage, EmbedType } from "@spacebar/schemas";
2121
import * as cheerio from "cheerio";
2222
import crypto from "crypto";
@@ -572,10 +572,6 @@ export async function dropDuplicateCacheEntries(entries: EmbedCache[]): Promise<
572572
);
573573
}
574574

575-
async function sleep(ms: number) {
576-
return new Promise((resolve) => setTimeout(resolve, ms));
577-
}
578-
579575
// hack to make nodejs not die
580576
function getSlowdownFactor(off: number) {
581577
if (off < 10) return off;

src/gateway/util/Utils.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Event, VoiceState } from "@spacebar/util";
1+
import { Event, Session, sleep, TimeSpan, VoiceState } from "@spacebar/util";
22
import { WebSocket } from "./WebSocket";
33
import { OPCODES } from "./Constants";
44
import { Send } from "./Send";
@@ -60,6 +60,21 @@ export async function cleanupOnStartup(): Promise<void> {
6060
VoiceState.clear()
6161
.then(() => console.log("[Gateway] Successfully cleaned voice states"))
6262
.catch((e) => console.error("[Gateway] Error cleaning voice states on startup:", e));
63+
64+
console.log("[Gateway] Starting async presence expiry...");
65+
expireOldPresenceStates()
66+
.then(() => console.log("[Gateway] Successfully cleaned expired presence states"))
67+
.catch((e) => console.error("[Gateway] Error cleaning expired presence states on startup:", e));
68+
}
69+
70+
async function expireOldPresenceStates() {
71+
for await (const session of await Session.createQueryBuilder("session").where("last_seen >= '2000/01/01' AND status != 'offline'").select().stream()) {
72+
// session object has all fields prefixed with `session_`... thanks typeorm
73+
if (TimeSpan.fromDates((session.session_last_seen as Date).getTime(), new Date().getTime()).totalMinutes > 30) {
74+
console.log(`[Gateway/util/Utils.ts] Expiring presence for session ${session.session_session_id} last seen at ${session.session_last_seen}`);
75+
await Session.update({ session_id: session.session_session_id }, { status: "offline" });
76+
}
77+
}
6378
}
6479

6580
export async function handleOffloadedGatewayRequest(socket: WebSocket, url: string, body: unknown) {

src/util/util/Token.ts

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -96,21 +96,6 @@ export const checkToken = (
9696
return rejectAndLog(reject, 401, "User not found");
9797
}
9898

99-
if (decoded.did && !session) {
100-
// temporary hack: create new session
101-
session = Session.create({
102-
session_id: decoded.did,
103-
user_id: user.id,
104-
is_admin_session: false,
105-
client_status: {},
106-
status: "online",
107-
client_info: {},
108-
});
109-
await session.save();
110-
logAuth("validateUser rejected: Session not found");
111-
return rejectAndLog(reject, 401, "Invalid Token");
112-
}
113-
11499
// we need to round it to seconds as it saved as seconds in jwt iat and valid_tokens_since is stored in milliseconds
115100
if (decoded.iat * 1000 < new Date(user.data.valid_tokens_since).setSeconds(0, 0)) {
116101
logAuth("validateUser rejected: Token not yet valid");
@@ -183,7 +168,7 @@ export async function generateToken(id: string, isAdminSession: boolean = false)
183168
user_id: id,
184169
is_admin_session: isAdminSession,
185170
client_status: {},
186-
status: "online",
171+
status: "offline", // will be set to online upon IDENTIFY
187172
client_info: {},
188173
});
189174
} while (await Session.findOne({ where: { session_id: newSession.session_id } }));

src/util/util/extensions/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
11
export * from "./Array";
2+
3+
// TODO: move to a separate file
4+
export async function sleep(ms: number) {
5+
return new Promise((resolve) => setTimeout(resolve, ms));
6+
}

0 commit comments

Comments
 (0)