diff --git a/README.md b/README.md index 052848a..5d0e7b9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # themepark-assistant -A tool for improving your trips to themepark - once developed +A tool for improving your trips to themeparks - once developed ## Testing Send request @@ -16,6 +16,12 @@ apply changes npx drizzle-kit push --config=drizzle-dev.config.ts ``` +## SQLite / D1 +Delete view +```sql +DROP VIEW IF EXISTS attraction_subscriptions; +``` + ## Cloudflare workers tricks If types are missing, run: ```bash @@ -36,4 +42,9 @@ npx wrangler dev --remote --test-scheduled Run curl request with cron expression ```bash curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*" -``` \ No newline at end of file +``` + +## Authentication endpoints +- /auth/signin -> Login +- /auth/signout -> Logout +- /auth/callback/github -> Callback for GitHub OAuth config \ No newline at end of file diff --git a/api/package-lock.json b/api/package-lock.json index 48b63ff..32b8800 100644 --- a/api/package-lock.json +++ b/api/package-lock.json @@ -6,9 +6,11 @@ "": { "name": "themepark-assistant", "dependencies": { + "@auth/core": "^0.40.0", + "@hono/auth-js": "^1.1.0", "dotenv": "^17.2.2", "drizzle-orm": "^0.44.5", - "hono": "^4.9.6" + "hono": "^4.9.9" }, "devDependencies": { "@types/node": "^24.3.1", @@ -17,6 +19,35 @@ "wrangler": "^4.4.0" } }, + "node_modules/@auth/core": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@auth/core/-/core-0.40.0.tgz", + "integrity": "sha512-n53uJE0RH5SqZ7N1xZoMKekbHfQgjd0sAEyUbE+IYJnmuQkbvuZnXItCU7d+i7Fj8VGOgqvNO7Mw4YfBTlZeQw==", + "license": "ISC", + "dependencies": { + "@panva/hkdf": "^1.2.1", + "jose": "^6.0.6", + "oauth4webapi": "^3.3.0", + "preact": "10.24.3", + "preact-render-to-string": "6.5.11" + }, + "peerDependencies": { + "@simplewebauthn/browser": "^9.0.1", + "@simplewebauthn/server": "^9.0.2", + "nodemailer": "^6.8.0" + }, + "peerDependenciesMeta": { + "@simplewebauthn/browser": { + "optional": true + }, + "@simplewebauthn/server": { + "optional": true + }, + "nodemailer": { + "optional": true + } + } + }, "node_modules/@cloudflare/kv-asset-handler": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.4.0.tgz", @@ -1023,6 +1054,20 @@ "node": ">=18" } }, + "node_modules/@hono/auth-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@hono/auth-js/-/auth-js-1.1.0.tgz", + "integrity": "sha512-GFlycQPDkuSbySTq8hvc73Fb9Wx0TnGff0BdE/v5wwrfC37SoNca5McD+nK94jxA0chggVYvn0CxH68uTylR5A==", + "license": "MIT", + "engines": { + "node": ">=18.4.0" + }, + "peerDependencies": { + "@auth/core": ">=0.35.0", + "hono": ">=3.0.0", + "react": "^18 || ^19 || ^19.0.0-rc" + } + }, "node_modules/@img/sharp-darwin-arm64": { "version": "0.33.5", "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", @@ -1431,6 +1476,15 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@panva/hkdf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", + "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/@poppinss/colors": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.5.tgz", @@ -1890,9 +1944,9 @@ "license": "BSD-2-Clause" }, "node_modules/hono": { - "version": "4.9.6", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.9.6.tgz", - "integrity": "sha512-doVjXhSFvYZ7y0dNokjwwSahcrAfdz+/BCLvAMa/vHLzjj8+CFyV5xteThGUsKdkaasgN+gF2mUxao+SGLpUeA==", + "version": "4.9.9", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.9.9.tgz", + "integrity": "sha512-Hxw4wT6zjJGZJdkJzAx9PyBdf7ZpxaTSA0NfxqjLghwMrLBX8p33hJBzoETRakF3UJu6OdNQBZAlNSkGqKFukw==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -1905,6 +1959,15 @@ "dev": true, "license": "MIT" }, + "node_modules/jose": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.0.tgz", + "integrity": "sha512-TTQJyoEoKcC1lscpVDCSsVgYzUDg/0Bt3WE//WiTPK6uOCQC2KZS4MpugbMWt/zyjkopgZoXhZuCi00gLudfUA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", @@ -1962,6 +2025,15 @@ "dev": true, "license": "MIT" }, + "node_modules/oauth4webapi": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.2.tgz", + "integrity": "sha512-FzZZ+bht5X0FKe7Mwz3DAVAmlH1BV5blSak/lHMBKz0/EBMhX6B10GlQYI51+oRp8ObJaX0g6pXrAxZh5s8rjw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/ohash": { "version": "2.0.11", "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", @@ -1983,6 +2055,35 @@ "dev": true, "license": "MIT" }, + "node_modules/preact": { + "version": "10.24.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz", + "integrity": "sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/preact-render-to-string": { + "version": "6.5.11", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.5.11.tgz", + "integrity": "sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==", + "license": "MIT", + "peerDependencies": { + "preact": ">=10" + } + }, + "node_modules/react": { + "version": "19.2.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz", + "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", diff --git a/api/package.json b/api/package.json index 53738a2..33b8b24 100644 --- a/api/package.json +++ b/api/package.json @@ -7,9 +7,11 @@ "cf-typegen": "wrangler types --env-interface CloudflareBindings" }, "dependencies": { + "@auth/core": "^0.40.0", + "@hono/auth-js": "^1.1.0", "dotenv": "^17.2.2", "drizzle-orm": "^0.44.5", - "hono": "^4.9.6" + "hono": "^4.9.9" }, "devDependencies": { "@types/node": "^24.3.1", diff --git a/api/src/db/schema.ts b/api/src/db/schema.ts index 90614c1..bc56e07 100644 --- a/api/src/db/schema.ts +++ b/api/src/db/schema.ts @@ -29,7 +29,13 @@ export const notificationMethod = sqliteTable('notification_method', { id: integer().primaryKey({ autoIncrement: true }), webhookUrl: text().notNull(), shownName: text().notNull(), - userId: integer().notNull().references(() => user.id) + userId: integer().notNull().references(() => user.id), + notificationProviderId: integer().notNull().references(() => notificationProvider.id), +}) + +export const notificationProvider = sqliteTable('notification_provider', { + id: integer().primaryKey({ autoIncrement: true }), + name: text().notNull().unique() }) export const themepark = sqliteTable('themepark', { @@ -59,9 +65,11 @@ export const attractionSubscriptions = sqliteView('attraction_subscriptions').as qb.selectDistinct({ attractionApiCode: sql`attraction.api_code`.as('attraction_api_code'), themeparkApiName: sql`themepark.api_name`.as('themepark_api_name'), - webhookUrl: sql`notification_method.webhook_url`.as('webhook_url') + webhookUrl: sql`notification_method.webhook_url`.as('webhook_url'), + notificationProviderName: sql`notification_provider.name`.as('notification_provider_name'), }).from(attractionNotification) .innerJoin(attraction, eq(attractionNotification.attractionId, attraction.id)) .innerJoin(themepark, eq(attraction.themeparkId, themepark.id)) .innerJoin(notificationMethod, eq(attractionNotification.notificationMethodId, notificationMethod.id)) + .innerJoin(notificationProvider, eq(notificationMethod.notificationProviderId, notificationProvider.id)) ); \ No newline at end of file diff --git a/api/src/index.ts b/api/src/index.ts index 3c71653..767b467 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono' -import { bearerAuth } from 'hono/bearer-auth' +import { authHandler, initAuthConfig, verifyAuth } from '@hono/auth-js' +import GitHub from '@auth/core/providers/github' import notification from './routes/notification' import logbook from './routes/logbook' import cronRouter from './jobs/cron' @@ -7,10 +8,26 @@ import cronRouter from './jobs/cron' // create app const app = new Hono() -// add bearer authentication -const token = 'insecure-token' +// OAuth via Auth.js +app.use('*', initAuthConfig((c) => ({ + secret: c.env.AUTH_SECRET, + providers: [ + GitHub({ + clientId: c.env.GITHUB_ID, + clientSecret: c.env.GITHUB_SECRET, + }) + ] +}))) -app.use('/*', bearerAuth({ token })) +app.use('/auth/*', authHandler()) + +app.use('/*', verifyAuth()) + +// example endpoint +app.get('/protected', (c) => { + const auth = c.get('authUser') + return c.json(auth) +}) // define routes & export app app.route('/notification', notification) diff --git a/api/src/jobs/cron.ts b/api/src/jobs/cron.ts index 85e0ad1..3212a2a 100644 --- a/api/src/jobs/cron.ts +++ b/api/src/jobs/cron.ts @@ -1,6 +1,7 @@ // Cron Router import { updateThemeparkData } from "./update-themepark-data"; import { batchAttractionImport } from "./update-attraction-list"; +import updateWaittimes from "./send-notifications"; export default async function cronRouter( event: ScheduledEvent, @@ -9,7 +10,7 @@ export default async function cronRouter( ){ switch (event.cron){ case '*/5 * * * *': - console.log('every 5 minutes'); + await updateWaittimes(env); break; case '0 1-6 7,14,21,28 * *': await batchAttractionImport(env, event.scheduledTime, event.cron); diff --git a/api/src/jobs/send-notifications.ts b/api/src/jobs/send-notifications.ts new file mode 100644 index 0000000..d3ee432 --- /dev/null +++ b/api/src/jobs/send-notifications.ts @@ -0,0 +1,159 @@ +import { AttractionImport, AttractionChanges } from "../types/attraction"; +import { getDbEnv } from '../db/client' +import { subscribedThemeparks, attractionSubscriptions } from "../db/schema"; +import { SubscribedThemeparks } from "../types/subscribed-themeparks"; +import { AttractionSubscription } from "../types/attraction-subscriptions"; +import httpRequest from "../lib/http-request"; +import fetchAttractions from "../lib/fetch-attractions"; + +/** + * Default function which connects all components to update the + * waittime in cache & send notification about changes in waittime. + * @param env Connection to Cloudflare + */ +export default async function updateWaittimes(env: Env): Promise{ + const db = getDbEnv(env); + const subscribedParks = await db.select().from(subscribedThemeparks); + const subscriptions = await db.select().from(attractionSubscriptions); + + for(let park of subscribedParks){ + const currentWaittimes = await fetchAttractions(park.apiName); + const cachedWaittimes = await getJsonFromKV(env, park.apiName, []); + + const changes = compareWaittimes(cachedWaittimes, currentWaittimes); + + if(changes.length > 0){ + await notifyAboutChanges(subscriptions, changes, park); + await cacheWaittimes(env, park.apiName, currentWaittimes); + } + } +} + +/** + * Saves the waittime of a specified themepark into KV namespace + * @param env KV connection + * @param themepark Themepark name to use as key in KV + * @param waittimes Object with the waittimes to save in cache + */ +async function cacheWaittimes(env: Env, themepark: string, waittimes: AttractionImport[]){ + await env.waittime_cache.put(themepark, JSON.stringify(waittimes)); +} + +/** + * Load value for specified key from KV and tries to parse as JSON + * @param env KV connection + * @param key Key to get value from + * @param defaultValue Default value to return if key is empty/not defined + * @returns Value of key from KV as defined type + */ +async function getJsonFromKV(env: Env, key: string, defaultValue: T): Promise{ + const cache = await env.waittime_cache.get(key); + if(!cache) return defaultValue; + + try{ + return JSON.parse(cache) as T; + } + catch(e){ + throw new Error(`Failed to parse JSON from KV, affected key: ${key}, error: ${e}`); + } +} + +/** + * Compares the waittimes of two objects from the type AttractionImport + * @param cached The cached/old object of the waittimes + * @param current The current object with the newer waittimes + * @returns An object of type AttractionChanges (booleans for changes -> increase) + */ +function compareWaittimes(cached: AttractionImport[], current: AttractionImport[]): AttractionChanges[]{ + const cachedMap = new Map(cached.map(obj => [obj.code, obj])); + let changes: AttractionChanges[] = []; + + current.forEach(attraction => { + const cachedTime = cachedMap.get(attraction.code)?.waitingtime; + const currentTime = attraction.waitingtime; + + if(attraction.status !== "opened") return; + + if((currentTime ?? 0) > (cachedTime ?? 0)){ + changes.push({ + apiCode: attraction.code, + name: attraction.name, + waittime: currentTime, + hasChanged: true, + increased: true + }); + } + else if((currentTime ?? 0) < (cachedTime ?? 0)){ + changes.push({ + apiCode: attraction.code, + name: attraction.name, + waittime: currentTime, + hasChanged: true, + increased: false + }) + } + }); + + return changes; +} + +/** + * Sends a message to a specified webhook endpoint + * @param webhookUrl The webhook's POST URL to send the request to + * @param message The message to send to the webhook + * @param type The type of notification (discord, slack, ntfy) + */ +// TODO: implement support for custom webhook providers (https://github.com/michivonah/themepark-assistant/issues/1) -> read templates from DB instead of switch case +async function sendNotification(webhookUrl: string, message: string, type: string): Promise{ + try{ + let body: Record | string; + + switch(type){ + case 'discord': + body = { + 'content':message + } + break; + case 'slack': + body = { + 'text':message + } + break; + case 'ntfy': + default: + body = message; + break; + } + + await httpRequest(webhookUrl, { + method:'POST', + body:body + }); + } + catch(e){ + throw new Error(`Failed to send notification: ${e}`); + } +} + +/** + * Sends notification about changes in waittime to a defined list of subscribers + * @param subscriptions Object of subscribed attractions with associated webhook URL + * @param changes Object of the changes at waittime + * @param themepark The API name of the themepark which should be checked for subscriptions + */ +async function notifyAboutChanges(subscriptions: AttractionSubscription[], changes: AttractionChanges[], themepark: SubscribedThemeparks){ + const changeMap = new Map(changes.map(c => [c.apiCode, c])); + + const subscribedChanges = subscriptions.filter(sub => + sub.themeparkApiName === themepark.apiName && changeMap.has(sub.attractionApiCode) + ); + + subscribedChanges.forEach(sub => { + const change = changeMap.get(sub.attractionApiCode); + + if(change && change.hasChanged){ + const message = `Waittime for ${change.name} ${change.increased ? 'increased' : 'sank'} to ${change.waittime} minutes!`; + sendNotification(sub.webhookUrl, message, sub.notificationProviderName); + } + }); +} \ No newline at end of file diff --git a/api/src/types/notification-provider.ts b/api/src/types/notification-provider.ts new file mode 100644 index 0000000..2d34ef7 --- /dev/null +++ b/api/src/types/notification-provider.ts @@ -0,0 +1,5 @@ +import { type InferSelectModel, type InferInsertModel } from 'drizzle-orm'; +import { notificationProvider } from '../db/schema'; + +export type NotificationProvider = InferInsertModel +export type NotificationProviderSelect = InferSelectModel \ No newline at end of file diff --git a/api/worker-configuration.d.ts b/api/worker-configuration.d.ts index aca371c..97901ea 100644 --- a/api/worker-configuration.d.ts +++ b/api/worker-configuration.d.ts @@ -1,11 +1,17 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: c639935623921ec3a10a77e49ca2a486) +// Generated by Wrangler by running `wrangler types` (hash: 95e16e3b0bf3458a0c120838843ae4f4) // Runtime types generated with workerd@1.20250902.0 2025-09-07 declare namespace Cloudflare { interface Env { + waittime_cache: KVNamespace; CLOUDFLARE_ACCOUNT_ID: string; CLOUDFLARE_DATABASE_ID: string; + CLOUDFLARE_DATABASE_ID_DEV: string; CLOUDFLARE_D1_TOKEN: string; + AUTH_SECRET: string; + AUTH_URL: string; + GITHUB_ID: string; + GITHUB_SECRET: string; d1_db: D1Database; } } diff --git a/api/wrangler.jsonc b/api/wrangler.jsonc index d3237bb..bbfbb86 100644 --- a/api/wrangler.jsonc +++ b/api/wrangler.jsonc @@ -30,6 +30,13 @@ "migrations_dir": "drizzle/migrations" } ], + "kv_namespaces": [ + { + "binding": "waittime_cache", + "id": "496e1b5c3a1d4211b5f63315dd1423e3", + "preview_id": "1a44ab1983f04d9e90d035b6f11ccb09" + } + ], "triggers": { "crons": [ "0 1-6 7,14,21,28 * *", // Each hour from 01:00 to 06:00 on day-of-month 7, 14, 21, and 28. -> update attraction list