1import { env } from '$env/dynamic/private';
2import SGDB from 'steamgriddb';
3import { get, writable } from 'svelte/store';
4
5const STEAM_ID = '76561198106829949';
6const GET_PLAYER_SUMMARY_ENDPOINT = `http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${env.STEAM_API_KEY}&steamids=${STEAM_ID}&format=json`;
7const LAST_GAME_FILE = `${env.WEBSITE_DATA_DIR}/last_game.json`;
8
9type LastGame = {
10 name: string;
11 link: string;
12 icon: string;
13 pfp: string;
14 when: number;
15 playing: boolean;
16};
17
18const steamgriddbClient = writable<SGDB | null>(null);
19const lastGame = writable<LastGame | null>(null);
20
21export const steamReadLastGame = async () => {
22 try {
23 const data = await Deno.readTextFile(LAST_GAME_FILE);
24 lastGame.set(JSON.parse(data));
25 } catch (why) {
26 console.log('could not read last game: ', why);
27 lastGame.set(null);
28 }
29};
30
31export const steamUpdateNowPlaying = async () => {
32 let griddbClient = get(steamgriddbClient);
33 if (griddbClient === null) {
34 griddbClient = new SGDB(env.STEAMGRIDDB_API_KEY);
35 steamgriddbClient.set(griddbClient);
36 }
37 try {
38 const profile = (await (await fetch(GET_PLAYER_SUMMARY_ENDPOINT)).json()).response.players[0];
39 if (!profile.gameid) {
40 lastGame.update((t) => {
41 if (t !== null) {
42 t.playing = false;
43 }
44 return t;
45 });
46 return;
47 }
48 const icons = await griddbClient.getIconsBySteamAppId(profile.gameid, ['official', 'custom']);
49 //console.log(icons)
50 const game: LastGame = {
51 name: profile.gameextrainfo,
52 link: `https://store.steampowered.com/app/${profile.gameid}`,
53 icon: icons[0].thumb.toString(),
54 pfp: profile.avatarmedium,
55 when: Date.now(),
56 playing: true
57 };
58 lastGame.set(game);
59 await Deno.writeTextFile(LAST_GAME_FILE, JSON.stringify(game));
60 } catch (why) {
61 console.log('could not fetch steam: ', why);
62 lastGame.update((t) => {
63 if (t !== null) {
64 t.playing = false;
65 }
66 return t;
67 });
68 }
69};
70
71export const getLastGame = () => {
72 return get(lastGame);
73};