- Notifications
You must be signed in to change notification settings - Fork0
[I2-17] Added backend events API#53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -35,3 +35,5 @@ yarn-error.log* | ||
| # typescript | ||
| *.tsbuildinfo | ||
| next-env.d.ts | ||
| *.env | ||
Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.
Uh oh!
There was an error while loading.Please reload this page.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import { RequestHandler } from "express"; | ||
| import { eventInfo } from "../data/eventData"; | ||
| export const EventsHandler: RequestHandler = (req, res) => { | ||
| res.status(200).json(eventInfo); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import crypto from "crypto"; | ||
| import { RequestHandler } from "express"; | ||
| import { eventInfo, eventInfoMutex, fetchEvent } from "../data/eventData"; | ||
| import { filterInPlace, replaceInPlace } from "../util"; | ||
| interface FacebookWebhookPayload { | ||
| object: string; | ||
| entry: Array<{ | ||
| id: string; | ||
| changes: Array<{ | ||
| field: string; | ||
| value: { | ||
| event_id: string; | ||
| item: string; | ||
| verb: string; | ||
| }; | ||
| }>; | ||
| }>; | ||
| } | ||
| const verifySignature = ( | ||
| rawBody: Buffer, | ||
| signatureHeader?: string | ||
| ): boolean => { | ||
| if (!signatureHeader) return false; | ||
| const [algo, signature] = signatureHeader.split("="); | ||
| if (algo !== "sha256") return false; | ||
| const expected = crypto | ||
| .createHmac("sha256", process.env.FB_APP_SECRET as string) | ||
| .update(rawBody) | ||
| .digest("hex"); | ||
| return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); | ||
| }; | ||
| export const EventsWebhookVerifier: RequestHandler = (req, res) => { | ||
| const mode = req.query["hub.mode"]; | ||
| const token = req.query["hub.verify_token"]; | ||
| const challenge = req.query["hub.challenge"]; | ||
| if (mode === "subscribe" && token === process.env.FB_WEBHOOK_VERIFY_TOKEN) { | ||
| return res.status(200).send(challenge); | ||
| } | ||
| res.sendStatus(403); | ||
| }; | ||
| /* | ||
| Sample webhook payload | ||
| https://developers.facebook.com/docs/graph-api/webhooks/getting-started/webhooks-for-pages -- for the outer wrapper | ||
| https://developers.facebook.com/docs/graph-api/webhooks/reference/page/#feed -- for the inner objects | ||
| { | ||
| "object": "page", | ||
| "entry": [ | ||
| { | ||
| "id": "PAGE_ID", | ||
| "time": 1623242342342, | ||
| "changes": [ | ||
| { | ||
| "field": "events", | ||
| "value": { | ||
| "event_id": "123456789", | ||
| "verb": "create", // also "edit" or "delete" | ||
| "published": 1 | ||
| } | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| } | ||
| */ | ||
| export const EventsWebhookUpdate: RequestHandler = async (req, res) => { | ||
| const signature = req.headers["x-hub-signature-256"]; | ||
| if ( | ||
| !req.rawBody || | ||
| typeof signature !== "string" || | ||
| !verifySignature(req.rawBody, signature) | ||
| ) { | ||
| return res.sendStatus(401); | ||
| } | ||
| const notif: FacebookWebhookPayload = req.body; | ||
| if ( | ||
| !notif || | ||
| !notif.entry || | ||
| notif.object !== "page" || | ||
| notif.entry.length === 0 | ||
| ) { | ||
| return res.sendStatus(400); | ||
| } | ||
| for (const entry of notif.entry) { | ||
| if (entry.id !== process.env.FB_EVENT_PAGE_ID) continue; | ||
| for (const change of entry.changes) { | ||
| if (change.field !== "feed" || change.value.item !== "event") continue; | ||
| try { | ||
| if (change.value.verb === "delete") { | ||
| await eventInfoMutex.runExclusive(() => | ||
| filterInPlace(eventInfo, (val) => val.id !== change.value.event_id) | ||
| ); | ||
| console.log(`Deleted event: ${change.value.event_id}`); | ||
| } else if (change.value.verb === "edit") { | ||
| const newEvent = await fetchEvent(change.value.event_id); | ||
| eventInfoMutex.runExclusive(() => | ||
| replaceInPlace( | ||
| eventInfo, | ||
| (val) => val.id === change.value.event_id, | ||
| newEvent | ||
| ) | ||
| ); | ||
| console.log(`Edited event: ${change.value.event_id}`); | ||
| } else if (change.value.verb === "add") { | ||
| const newEvent = await fetchEvent(change.value.event_id); | ||
| await eventInfoMutex.runExclusive(() => eventInfo.push(newEvent)); | ||
| console.log(`Added event: ${change.value.event_id}`); | ||
| } else { | ||
| console.warn( | ||
| `Unknown verb "${change.value.verb}" for event ${change.value.event_id}` | ||
| ); | ||
| } | ||
| } catch (err) { | ||
| console.error( | ||
| `Error processing event: ${change.value.event_id}:\n${err}` | ||
| ); | ||
| return res.sendStatus(500); | ||
| } | ||
| } | ||
| } | ||
| res.sendStatus(200); | ||
| }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { Mutex } from "async-mutex"; | ||
| import { inspect } from "util"; | ||
| import { FacebookError, Result, ResultType } from "../util"; | ||
| class EventInfo { | ||
| // god forbid a class have public members | ||
| public id: string; | ||
| public title: string; | ||
| public startTime: string; | ||
| public endTime?: string; | ||
| public location: string; | ||
| public imageUrl: string; | ||
| public link: string; | ||
| constructor( | ||
| id: string, | ||
| title: string, | ||
| startTime: string, | ||
| endTime: string | undefined, | ||
| location: string, | ||
| imageUrl: string | ||
| ) { | ||
| this.id = id; | ||
| this.title = title; | ||
| this.startTime = startTime; | ||
| this.endTime = endTime; | ||
| this.location = location; | ||
| this.imageUrl = imageUrl; | ||
| // would use link as getter but getters are not enumerable so it doesn't appear in JSON.stringify :skull: | ||
| // maybe a cursed fix would be to use Object.defineProperty LOL | ||
| this.link = `https://www.facebook.com/events/${id}`; | ||
| } | ||
| } | ||
| interface FacebookEvent { | ||
| id: string; | ||
| name: string; | ||
| cover?: { source: string }; | ||
| place?: { name: string }; | ||
| start_time: string; | ||
| end_time?: string; | ||
| } | ||
| interface FacebookEventsResponse { | ||
| data: FacebookEvent[]; | ||
| } | ||
| // this isn't in .env for different module compatiblity | ||
| const FB_API_VERSION = "v23.0"; | ||
| const DEFAULT_EVENT_LOCATION = "Everything everywhere all at once!!!"; | ||
| const DEFAULT_EVENT_IMAGE = "/images/events/default_event.jpg"; | ||
| // we LOVE global variables | ||
| export const eventInfoMutex = new Mutex(); | ||
| export const eventInfo: EventInfo[] = []; | ||
| export async function fetchEvents() { | ||
| const response = await fetch( | ||
| `https://graph.facebook.com/${FB_API_VERSION}/${process.env.FB_EVENT_PAGE_ID}/events?access_token=${process.env.FB_ACCESS_TOKEN}&fields=id,name,cover,place,start_time,end_time` | ||
| ); | ||
| const res: Result<FacebookEventsResponse, FacebookError> = await response.json(); | ||
| if (!res || res.type === ResultType.Err) { | ||
| console.log(`No events found...\n${res}`); | ||
| return []; | ||
| } | ||
| const processed = res.value.data.map( | ||
| (e) => | ||
| new EventInfo( | ||
| e.id, | ||
| e.name, | ||
| e.start_time, | ||
| e.end_time, | ||
| e.place?.name ?? DEFAULT_EVENT_LOCATION, | ||
| e.cover?.source ?? DEFAULT_EVENT_IMAGE | ||
| ) | ||
| ); | ||
| return processed; | ||
| } | ||
| export async function fetchEvent(id: string) { | ||
| const response = await fetch( | ||
| `https://graph.facebook.com/${FB_API_VERSION}/${id}?access_token=${process.env.FB_ACCESS_TOKEN}&fields=id,name,cover,place,start_time,end_time` | ||
| ); | ||
| const res: Result<FacebookEvent, FacebookError> = await response.json(); | ||
| if (!res || res.type === ResultType.Err) { | ||
| throw new Error( | ||
| `Couldn't fetch details for event ${id}\n${inspect( | ||
| Object.getOwnPropertyDescriptor(res, "error")?.value | ||
| )}` | ||
| ); | ||
| } | ||
| return new EventInfo( | ||
| res.value.id, | ||
| res.value.name, | ||
| res.value.start_time, | ||
| res.value.end_time, | ||
| res.value.place?.name ?? DEFAULT_EVENT_LOCATION, | ||
| res.value.cover?.source ?? DEFAULT_EVENT_IMAGE | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import { Router } from "express"; | ||
| import { EventsHandler } from "../controllers/events"; | ||
| const router = Router(); | ||
| router.get("/events", EventsHandler); | ||
| export default router; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import { Router } from "express"; | ||
| import { EventsWebhookUpdate, EventsWebhookVerifier } from "../controllers/eventsWebhook"; | ||
| const router = Router(); | ||
| router.post("/eventsWebhook", EventsWebhookUpdate); | ||
| router.get("/eventsWebhook", EventsWebhookVerifier); | ||
| export default router; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import "express"; | ||
| declare module "express-serve-static-core" { | ||
| interface Request { | ||
| rawBody?: Buffer; | ||
| } | ||
| interface IncomingMessage { | ||
| rawBody?: Buffer; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import "http"; | ||
| declare module "http" { | ||
| interface IncomingMessage { | ||
| rawBody?: Buffer; | ||
| } | ||
| } |
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.