Refactors video integrations (#1037)

* Fixes error types

* Type fixes

* Refactors video meeting handling

* More type fixes

* Type fixes

* More fixes

* Makes language non optional

* Adds missing translations

* Apply suggestions from code review

Co-authored-by: Alex Johansson <[email protected]>

* Feedback

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Alex Johansson <[email protected]>
This commit is contained in:
authored and GitHub committed 2021-10-26 10:17:24 -06:00
1 parent eabb096e14
commit e38086b8fe
17 files changed
+618 -612

No files matched your search

+1 -2
View File
@@ -1,4 +1,5 @@
// import { getBusyVideoTimes } from "@lib/videoClient";
import { Prisma } from "@prisma/client";
import dayjs from "dayjs";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -6,8 +7,6 @@ import { asStringOrNull } from "@lib/asStringOrNull";
import { getBusyCalendarTimes } from "@lib/calendarClient";
import prisma from "@lib/prisma";
import { Prisma } from ".prisma/client";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const user = asStringOrNull(req.query.user);
const dateFrom = dayjs(asStringOrNull(req.query.dateFrom));
+7 -4
View File
@@ -7,6 +7,7 @@ import { CalendarEvent } from "@lib/calendarClient";
import EventRejectionMail from "@lib/emails/EventRejectionMail";
import EventManager from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { BookingConfirmBody } from "@lib/types/booking";
import { getTranslation } from "@server/lib/i18n";
@@ -18,7 +19,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(401).json({ message: "Not authenticated" });
}
const bookingId = req.body.id;
const reqBody = req.body as BookingConfirmBody;
const bookingId = reqBody.id;
if (!bookingId) {
return res.status(400).json({ message: "bookingId missing" });
}
@@ -60,7 +63,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
if (!booking || booking.userId != currentUser.id) {
if (!booking || booking.userId !== currentUser.id) {
return res.status(404).json({ message: "booking not found" });
}
if (booking.confirmed) {
@@ -75,12 +78,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
endTime: booking.endTime.toISOString(),
organizer: { email: currentUser.email, name: currentUser.name!, timeZone: currentUser.timeZone },
attendees: booking.attendees,
location: booking.location,
location: booking.location ?? "",
uid: booking.uid,
language: t,
};
if (req.body.confirmed) {
if (reqBody.confirmed) {
const eventManager = new EventManager(currentUser.credentials);
const scheduleResult = await eventManager.create(evt);
+6 -43
View File
@@ -15,7 +15,7 @@ import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import EventOrganizerRequestMail from "@lib/emails/EventOrganizerRequestMail";
import { getErrorFromUnknown } from "@lib/errors";
import { getEventName } from "@lib/event";
import EventManager, { CreateUpdateResult, EventResult, PartialReference } from "@lib/events/EventManager";
import EventManager, { EventResult, PartialReference } from "@lib/events/EventManager";
import logger from "@lib/logger";
import prisma from "@lib/prisma";
import { BookingCreateBody } from "@lib/types/booking";
@@ -329,6 +329,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
let booking: Booking | null = null;
try {
booking = await createBooking();
evt.uid = booking.uid;
} catch (_err) {
const err = getErrorFromUnknown(_err);
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", err.message);
@@ -431,7 +432,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (rescheduleUid) {
// Use EventManager to conditionally use all needed integrations.
const eventManagerCalendarEvent = { ...evt, uid: rescheduleUid };
const updateResults: CreateUpdateResult = await eventManager.update(eventManagerCalendarEvent);
const updateResults = await eventManager.update(eventManagerCalendarEvent);
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
@@ -444,9 +445,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
log.error(`Booking ${user.name} failed`, error, results);
}
// If it's not a reschedule, doesn't require confirmation and there's no price,
// Create a booking
} else if (!eventType.requiresConfirmation && !eventType.price) {
// Use EventManager to conditionally use all needed integrations.
const createResults: CreateUpdateResult = await eventManager.create(evt);
const createResults = await eventManager.create(evt);
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
@@ -461,46 +464,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
}
//for Daily.co video calls will grab the meeting token for the call
const isDaily = evt.location === "integrations:daily";
let dailyEvent: DailyReturnType;
if (!rescheduleUid) {
dailyEvent = results.filter((ref) => ref.type === "daily")[0]?.createdEvent as DailyReturnType;
} else {
dailyEvent = results.filter((ref) => ref.type === "daily_video")[0]?.updatedEvent as DailyReturnType;
}
let meetingToken;
if (isDaily) {
const response = await fetch("https://api.daily.co/v1/meeting-tokens", {
method: "POST",
body: JSON.stringify({ properties: { room_name: dailyEvent.name, is_owner: true } }),
headers: {
Authorization: "Bearer " + process.env.DAILY_API_KEY,
"Content-Type": "application/json",
},
});
meetingToken = await response.json();
}
//for Daily.co video calls will update the dailyEventReference table
if (isDaily) {
await prisma.dailyEventReference.create({
data: {
dailyurl: dailyEvent.url,
dailytoken: meetingToken.token,
booking: {
connect: {
uid: booking.uid,
},
},
},
});
}
if (eventType.requiresConfirmation && !rescheduleUid) {
await new EventOrganizerRequestMail({ ...evt, uid }).sendEmail();
}
+26 -13
View File
@@ -1,19 +1,21 @@
import { BookingStatus } from "@prisma/client";
import async from "async";
import { NextApiRequest, NextApiResponse } from "next";
import { refund } from "@ee/lib/stripe/server";
import { asStringOrNull } from "@lib/asStringOrNull";
import { getSession } from "@lib/auth";
import { CalendarEvent, deleteEvent } from "@lib/calendarClient";
import { FAKE_DAILY_CREDENTIAL } from "@lib/integrations/Daily/DailyVideoApiAdapter";
import prisma from "@lib/prisma";
import { deleteMeeting } from "@lib/videoClient";
import sendPayload from "@lib/webhooks/sendPayload";
import getSubscriberUrls from "@lib/webhooks/subscriberUrls";
import { dailyDeleteMeeting } from "../../lib/dailyVideoClient";
import { getTranslation } from "@server/lib/i18n";
export default async function handler(req, res) {
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// just bail if it not a DELETE
if (req.method !== "DELETE" && req.method !== "POST") {
return res.status(405).end();
@@ -48,7 +50,6 @@ export default async function handler(req, res) {
},
payment: true,
paid: true,
location: true,
title: true,
description: true,
startTime: true,
@@ -62,32 +63,45 @@ export default async function handler(req, res) {
return res.status(404).end();
}
if ((!session || session.user?.id != bookingToDelete.user?.id) && bookingToDelete.startTime < new Date()) {
if ((!session || session.user?.id !== bookingToDelete.user?.id) && bookingToDelete.startTime < new Date()) {
return res.status(403).json({ message: "Cannot cancel past events" });
}
if (!bookingToDelete.userId) {
return res.status(404).json({ message: "User not found" });
}
const organizer = await prisma.user.findFirst({
where: {
id: bookingToDelete.userId as number,
id: bookingToDelete.userId,
},
select: {
name: true,
email: true,
timeZone: true,
},
rejectOnNotFound: true,
});
const t = await getTranslation(req.body.language ?? "en", "common");
const evt: CalendarEvent = {
type: bookingToDelete?.title,
title: bookingToDelete?.title,
description: bookingToDelete?.description || "",
startTime: bookingToDelete?.startTime.toString(),
endTime: bookingToDelete?.endTime.toString(),
organizer: organizer,
organizer: {
email: organizer.email,
name: organizer.name ?? "Nameless",
timeZone: organizer.timeZone,
},
attendees: bookingToDelete?.attendees.map((attendee) => {
const retObj = { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
return retObj;
}),
uid: bookingToDelete?.uid,
language: t,
};
// Hook up the webhook logic here
@@ -112,6 +126,10 @@ export default async function handler(req, res) {
},
});
if (bookingToDelete.location === "integrations:daily") {
bookingToDelete.user.credentials.push(FAKE_DAILY_CREDENTIAL);
}
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential) => {
const bookingRefUid = bookingToDelete.references.filter((ref) => ref.type === credential.type)[0]?.uid;
if (bookingRefUid) {
@@ -121,13 +139,6 @@ export default async function handler(req, res) {
return await deleteMeeting(credential, bookingRefUid);
}
}
//deleting a Daily meeting
const isDaily = bookingToDelete.location === "integrations:daily";
const bookingUID = bookingToDelete.references.filter((ref) => ref.type === "daily")[0]?.uid;
if (isDaily) {
return await dailyDeleteMeeting(credential, bookingUID);
}
});
if (bookingToDelete && bookingToDelete.paid) {
@@ -144,6 +155,8 @@ export default async function handler(req, res) {
},
attendees: bookingToDelete.attendees,
location: bookingToDelete.location ?? "",
uid: bookingToDelete.uid ?? "",
language: t,
};
await refund(bookingToDelete, evt);
await prisma.booking.update({
+8 -1
View File
@@ -6,6 +6,8 @@ import { CalendarEvent } from "@lib/calendarClient";
import EventOrganizerRequestReminderMail from "@lib/emails/EventOrganizerRequestReminderMail";
import prisma from "@lib/prisma";
import { getTranslation } from "@server/lib/i18n";
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const apiKey = req.headers.authorization || req.query.apiKey;
if (process.env.CRON_API_KEY !== apiKey) {
@@ -31,6 +33,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
select: {
title: true,
description: true,
location: true,
startTime: true,
endTime: true,
attendees: true,
@@ -59,10 +62,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
console.error(`Booking ${booking.id} is missing required properties for booking reminder`, { user });
continue;
}
const t = await getTranslation(req.body.language ?? "en", "common");
const evt: CalendarEvent = {
type: booking.title,
title: booking.title,
description: booking.description || undefined,
location: booking.location ?? "",
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
organizer: {
@@ -71,9 +76,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
timeZone: user.timeZone,
},
attendees: booking.attendees,
uid: booking.uid,
language: t,
};
await new EventOrganizerRequestReminderMail(evt, booking.uid).sendEmail();
await new EventOrganizerRequestReminderMail(evt).sendEmail();
await prisma.reminderMail.create({
data: {
referenceId: booking.id,