Skip to content

Commit

Permalink
session log
Browse files Browse the repository at this point in the history
  • Loading branch information
mallsoft committed Feb 11, 2024
1 parent c5f3e8e commit 640b2e7
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.35.1",
"matter-js": "^0.19.0",
"pocketbase": "^0.21.1",
"prettier": "^3.2.5",
"prettier-plugin-svelte": "^3.1.2",
"svelte": "^4.2.10",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions src/lib/components/Bacon.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script lang="ts">
let time = Date.now();
const handleSessionChange = () => {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon(
'/api/bacon',
JSON.stringify({ timeSpent: Math.round((Date.now() - time) / 1000) })
);
time = Date.now();
}
};
</script>

<svelte:window on:visibilitychange={handleSessionChange} />
2 changes: 2 additions & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import { isLocalStorageAvailable } from '$lib/utils';
import Snowy from '$lib/components/visuals/Snowy.svelte';
import { page } from '$app/stores';
import Bacon from '$lib/components/Bacon.svelte';
</script>

<Meta />
Expand All @@ -30,6 +31,7 @@

{#if isLocalStorageAvailable()}
<Achievements />
<Bacon />
{/if}

<Terminus />
Expand Down
20 changes: 20 additions & 0 deletions src/routes/api/bacon/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { env } from '$env/dynamic/private';
import { getRequestInfos } from '$lib/utils';
import type { RequestHandler } from './$types';
import PocketBase from 'pocketbase';

const pb = new PocketBase(env.SECRET_URL);

export const POST: RequestHandler = async (event) => {
const { agent, os, platform } = getRequestInfos(event);
let uid = event.cookies.get('baconx');
if (!uid) uid = crypto.randomUUID();
event.cookies.set('baconx', uid, { path: '/', maxAge: 7200 });

const resp = await event.request.json();

await pb.collection('machine').authWithPassword('mallx', env.SECRET_MALLX);
await pb.collection('stats').create({ timeSpent: resp.timeSpent, agent, os, platform, uid });

return new Response();
};

0 comments on commit 640b2e7

Please sign in to comment.