Skip to content

Commit

Permalink
memelytics
Browse files Browse the repository at this point in the history
  • Loading branch information
mallsoft committed Feb 11, 2024
1 parent 640b2e7 commit 19e0bdf
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
14 changes: 13 additions & 1 deletion src/lib/components/Bacon.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
<script lang="ts">
import { navigating } from '$app/stores';
import { unlocked } from './achievement/achievementStores';
let time = Date.now();
let navigations = 0;
$: if ($navigating) navigations++;
const handleSessionChange = () => {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon(
'/api/bacon',
JSON.stringify({ timeSpent: Math.round((Date.now() - time) / 1000) })
JSON.stringify({
timeSpent: Math.round((Date.now() - time) / 1000),
window: `${window.innerWidth}x${window.innerHeight}`,
achievements: $unlocked.length,
navigations
})
);
time = Date.now();
Expand Down
26 changes: 20 additions & 6 deletions src/routes/api/bacon/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,28 @@ 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();
const { timeSpent, window, achievements, navigations } = await event.request.json();

const id = event.cookies.get('baconx');
await pb.collection('machine').authWithPassword('mallx', env.SECRET_MALLX);
await pb.collection('stats').create({ timeSpent: resp.timeSpent, agent, os, platform, uid });

if (id) {
await pb.collection('stats').update(id, {
'timeSpent+': timeSpent,
'navigations+': navigations,
agent,
os,
platform,
window,
achievements
});
event.cookies.set('baconx', id, { path: '/', maxAge: 7200 });
} else {
const entry = await pb
.collection('stats')
.create({ timeSpent, navigations, agent, os, platform, window, achievements });
event.cookies.set('baconx', entry.id, { path: '/', maxAge: 7200 });
}

return new Response();
};

0 comments on commit 19e0bdf

Please sign in to comment.