diff --git a/README.md b/README.md index 5d0e7b9..052848a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # themepark-assistant -A tool for improving your trips to themeparks - once developed +A tool for improving your trips to themepark - once developed ## Testing Send request @@ -16,12 +16,6 @@ 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 @@ -42,9 +36,4 @@ npx wrangler dev --remote --test-scheduled Run curl request with cron expression ```bash curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*" -``` - -## Authentication endpoints -- /auth/signin -> Login -- /auth/signout -> Logout -- /auth/callback/github -> Callback for GitHub OAuth config \ No newline at end of file +``` \ No newline at end of file diff --git a/api/package-lock.json b/api/package-lock.json index 32b8800..48b63ff 100644 --- a/api/package-lock.json +++ b/api/package-lock.json @@ -6,11 +6,9 @@ "": { "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.9" + "hono": "^4.9.6" }, "devDependencies": { "@types/node": "^24.3.1", @@ -19,35 +17,6 @@ "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", @@ -1054,20 +1023,6 @@ "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", @@ -1476,15 +1431,6 @@ "@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", @@ -1944,9 +1890,9 @@ "license": "BSD-2-Clause" }, "node_modules/hono": { - "version": "4.9.9", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.9.9.tgz", - "integrity": "sha512-Hxw4wT6zjJGZJdkJzAx9PyBdf7ZpxaTSA0NfxqjLghwMrLBX8p33hJBzoETRakF3UJu6OdNQBZAlNSkGqKFukw==", + "version": "4.9.6", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.9.6.tgz", + "integrity": "sha512-doVjXhSFvYZ7y0dNokjwwSahcrAfdz+/BCLvAMa/vHLzjj8+CFyV5xteThGUsKdkaasgN+gF2mUxao+SGLpUeA==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -1959,15 +1905,6 @@ "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", @@ -2025,15 +1962,6 @@ "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", @@ -2055,35 +1983,6 @@ "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 33b8b24..53738a2 100644 --- a/api/package.json +++ b/api/package.json @@ -7,11 +7,9 @@ "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.9" + "hono": "^4.9.6" }, "devDependencies": { "@types/node": "^24.3.1", diff --git a/api/src/db/schema.ts b/api/src/db/schema.ts index bc56e07..90614c1 100644 --- a/api/src/db/schema.ts +++ b/api/src/db/schema.ts @@ -29,13 +29,7 @@ export const notificationMethod = sqliteTable('notification_method', { id: integer().primaryKey({ autoIncrement: true }), webhookUrl: text().notNull(), shownName: text().notNull(), - 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() + userId: integer().notNull().references(() => user.id) }) export const themepark = sqliteTable('themepark', { @@ -65,11 +59,9 @@ 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'), - notificationProviderName: sql`notification_provider.name`.as('notification_provider_name'), + webhookUrl: sql`notification_method.webhook_url`.as('webhook_url') }).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 767b467..3c71653 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -1,6 +1,5 @@ import { Hono } from 'hono' -import { authHandler, initAuthConfig, verifyAuth } from '@hono/auth-js' -import GitHub from '@auth/core/providers/github' +import { bearerAuth } from 'hono/bearer-auth' import notification from './routes/notification' import logbook from './routes/logbook' import cronRouter from './jobs/cron' @@ -8,26 +7,10 @@ import cronRouter from './jobs/cron' // create app const app = new Hono() -// 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, - }) - ] -}))) +// add bearer authentication +const token = 'insecure-token' -app.use('/auth/*', authHandler()) - -app.use('/*', verifyAuth()) - -// example endpoint -app.get('/protected', (c) => { - const auth = c.get('authUser') - return c.json(auth) -}) +app.use('/*', bearerAuth({ token })) // define routes & export app app.route('/notification', notification) diff --git a/api/src/jobs/cron.ts b/api/src/jobs/cron.ts index 3212a2a..85e0ad1 100644 --- a/api/src/jobs/cron.ts +++ b/api/src/jobs/cron.ts @@ -1,7 +1,6 @@ // 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, @@ -10,7 +9,7 @@ export default async function cronRouter( ){ switch (event.cron){ case '*/5 * * * *': - await updateWaittimes(env); + console.log('every 5 minutes'); 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 deleted file mode 100644 index d3ee432..0000000 --- a/api/src/jobs/send-notifications.ts +++ /dev/null @@ -1,159 +0,0 @@ -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 deleted file mode 100644 index 2d34ef7..0000000 --- a/api/src/types/notification-provider.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 97901ea..aca371c 100644 --- a/api/worker-configuration.d.ts +++ b/api/worker-configuration.d.ts @@ -1,17 +1,11 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 95e16e3b0bf3458a0c120838843ae4f4) +// Generated by Wrangler by running `wrangler types` (hash: c639935623921ec3a10a77e49ca2a486) // 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 bbfbb86..d3237bb 100644 --- a/api/wrangler.jsonc +++ b/api/wrangler.jsonc @@ -30,13 +30,6 @@ "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