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:
17 files changed
+618
-612
No files matched your search
@@ -0,0 +1,131 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { CalendarEvent } from "@lib/calendarClient";
|
||||
import { handleErrorsJson } from "@lib/errors";
|
||||
import prisma from "@lib/prisma";
|
||||
import { VideoApiAdapter } from "@lib/videoClient";
|
||||
|
||||
export interface DailyReturnType {
|
||||
/** Long UID string ie: 987b5eb5-d116-4a4e-8e2c-14fcb5710966 */
|
||||
id: string;
|
||||
/** Not a real name, just a random generated string ie: "ePR84NQ1bPigp79dDezz" */
|
||||
name: string;
|
||||
api_created: boolean;
|
||||
privacy: "private" | "public";
|
||||
/** https://api-demo.daily.co/ePR84NQ1bPigp79dDezz */
|
||||
url: string;
|
||||
created_at: string;
|
||||
config: {
|
||||
nbf: number;
|
||||
exp: number;
|
||||
enable_chat: boolean;
|
||||
enable_knocking: boolean;
|
||||
enable_prejoin_ui: boolean;
|
||||
enable_new_call_ui: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DailyEventResult {
|
||||
id: string;
|
||||
name: string;
|
||||
api_created: boolean;
|
||||
privacy: string;
|
||||
url: string;
|
||||
created_at: string;
|
||||
config: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface DailyVideoCallData {
|
||||
type: string;
|
||||
id: string;
|
||||
password: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type DailyKey = {
|
||||
apikey: string;
|
||||
};
|
||||
|
||||
export const FAKE_DAILY_CREDENTIAL: Credential = {
|
||||
id: +new Date().getTime(),
|
||||
type: "daily_video",
|
||||
key: { apikey: process.env.DAILY_API_KEY },
|
||||
userId: +new Date().getTime(),
|
||||
};
|
||||
|
||||
const DailyVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
|
||||
const dailyApiToken = (credential.key as DailyKey).apikey;
|
||||
|
||||
function postToDailyAPI(endpoint: string, body: Record<string, any>) {
|
||||
return fetch("https://api.daily.co/v1" + endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + dailyApiToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
async function createOrUpdateMeeting(endpoint: string, event: CalendarEvent) {
|
||||
if (!event.uid) {
|
||||
throw new Error("We need need the booking uid to create the Daily reference in DB");
|
||||
}
|
||||
const response = await postToDailyAPI(endpoint, translateEvent(event));
|
||||
const dailyEvent: DailyReturnType = await handleErrorsJson(response);
|
||||
const res = await postToDailyAPI("/meeting-tokens", {
|
||||
properties: { room_name: dailyEvent.name, is_owner: true },
|
||||
});
|
||||
const meetingToken: { token: string } = await handleErrorsJson(res);
|
||||
await prisma.dailyEventReference.create({
|
||||
data: {
|
||||
dailyurl: dailyEvent.url,
|
||||
dailytoken: meetingToken.token,
|
||||
booking: {
|
||||
connect: {
|
||||
uid: event.uid,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return dailyEvent;
|
||||
}
|
||||
|
||||
const translateEvent = (event: CalendarEvent) => {
|
||||
// Documentation at: https://docs.daily.co/reference#list-rooms
|
||||
// added a 1 hour buffer for room expiration and room entry
|
||||
const exp = Math.round(new Date(event.endTime).getTime() / 1000) + 60 * 60;
|
||||
const nbf = Math.round(new Date(event.startTime).getTime() / 1000) - 60 * 60;
|
||||
return {
|
||||
privacy: "private",
|
||||
properties: {
|
||||
enable_new_call_ui: true,
|
||||
enable_prejoin_ui: true,
|
||||
enable_knocking: true,
|
||||
enable_screenshare: true,
|
||||
enable_chat: true,
|
||||
exp: exp,
|
||||
nbf: nbf,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
/** Daily doesn't need to return busy times, so we return empty */
|
||||
getAvailability: () => {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
createMeeting: async (event: CalendarEvent) => createOrUpdateMeeting("/rooms", event),
|
||||
deleteMeeting: (uid: string) =>
|
||||
fetch("https://api.daily.co/v1/rooms/" + uid, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + dailyApiToken,
|
||||
},
|
||||
}).then(handleErrorsJson),
|
||||
updateMeeting: (uid: string, event: CalendarEvent) => createOrUpdateMeeting("/rooms/" + uid, event),
|
||||
};
|
||||
};
|
||||
|
||||
export default DailyVideoApiAdapter;
|
||||
@@ -0,0 +1,205 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { CalendarEvent } from "@lib/calendarClient";
|
||||
import { handleErrorsJson, handleErrorsRaw } from "@lib/errors";
|
||||
import prisma from "@lib/prisma";
|
||||
import { VideoApiAdapter } from "@lib/videoClient";
|
||||
|
||||
/** @link https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate */
|
||||
export interface ZoomEventResult {
|
||||
created_at: string;
|
||||
duration: number;
|
||||
host_id: string;
|
||||
id: number;
|
||||
join_url: string;
|
||||
settings: {
|
||||
alternative_hosts: string;
|
||||
approval_type: number;
|
||||
audio: string;
|
||||
auto_recording: string;
|
||||
close_registration: boolean;
|
||||
cn_meeting: boolean;
|
||||
enforce_login: boolean;
|
||||
enforce_login_domains: string;
|
||||
global_dial_in_countries: string[];
|
||||
global_dial_in_numbers: {
|
||||
city: string;
|
||||
country: string;
|
||||
country_name: string;
|
||||
number: string;
|
||||
type: string;
|
||||
}[];
|
||||
breakout_room: {
|
||||
enable: boolean;
|
||||
rooms: {
|
||||
name: string;
|
||||
participants: string[];
|
||||
}[];
|
||||
host_video: boolean;
|
||||
in_meeting: boolean;
|
||||
join_before_host: boolean;
|
||||
mute_upon_entry: boolean;
|
||||
participant_video: boolean;
|
||||
registrants_confirmation_email: boolean;
|
||||
use_pmi: boolean;
|
||||
waiting_room: boolean;
|
||||
watermark: boolean;
|
||||
registrants_email_notification: boolean;
|
||||
};
|
||||
start_time: string;
|
||||
start_url: string;
|
||||
status: string;
|
||||
timezone: string;
|
||||
topic: string;
|
||||
type: number;
|
||||
uuid: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ZoomToken {
|
||||
scope: "meeting:write";
|
||||
expires_in: number;
|
||||
token_type: "bearer";
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
const zoomAuth = (credential: Credential) => {
|
||||
const credentialKey = credential.key as unknown as ZoomToken;
|
||||
const isExpired = (expiryDate: number) => expiryDate < +new Date();
|
||||
const authHeader =
|
||||
"Basic " +
|
||||
Buffer.from(process.env.ZOOM_CLIENT_ID + ":" + process.env.ZOOM_CLIENT_SECRET).toString("base64");
|
||||
|
||||
const refreshAccessToken = (refreshToken: string) =>
|
||||
fetch("https://zoom.us/oauth/token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
refresh_token: refreshToken,
|
||||
grant_type: "refresh_token",
|
||||
}),
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then(async (responseBody) => {
|
||||
// Store new tokens in database.
|
||||
await prisma.credential.update({
|
||||
where: {
|
||||
id: credential.id,
|
||||
},
|
||||
data: {
|
||||
key: responseBody,
|
||||
},
|
||||
});
|
||||
credentialKey.access_token = responseBody.access_token;
|
||||
credentialKey.expires_in = Math.round(+new Date() / 1000 + responseBody.expires_in);
|
||||
return credentialKey.access_token;
|
||||
});
|
||||
|
||||
return {
|
||||
getToken: () =>
|
||||
!isExpired(credentialKey.expires_in)
|
||||
? Promise.resolve(credentialKey.access_token)
|
||||
: refreshAccessToken(credentialKey.refresh_token),
|
||||
};
|
||||
};
|
||||
|
||||
const ZoomVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
|
||||
const auth = zoomAuth(credential);
|
||||
|
||||
const translateEvent = (event: CalendarEvent) => {
|
||||
// Documentation at: https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate
|
||||
return {
|
||||
topic: event.title,
|
||||
type: 2, // Means that this is a scheduled meeting
|
||||
start_time: event.startTime,
|
||||
duration: (new Date(event.endTime).getTime() - new Date(event.startTime).getTime()) / 60000,
|
||||
//schedule_for: "string", TODO: Used when scheduling the meeting for someone else (needed?)
|
||||
timezone: event.attendees[0].timeZone,
|
||||
//password: "string", TODO: Should we use a password? Maybe generate a random one?
|
||||
agenda: event.description,
|
||||
settings: {
|
||||
host_video: true,
|
||||
participant_video: true,
|
||||
cn_meeting: false, // TODO: true if host meeting in China
|
||||
in_meeting: false, // TODO: true if host meeting in India
|
||||
join_before_host: true,
|
||||
mute_upon_entry: false,
|
||||
watermark: false,
|
||||
use_pmi: false,
|
||||
approval_type: 2,
|
||||
audio: "both",
|
||||
auto_recording: "none",
|
||||
enforce_login: false,
|
||||
registrants_email_notification: true,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
getAvailability: () => {
|
||||
return auth
|
||||
.getToken()
|
||||
.then(
|
||||
// TODO Possibly implement pagination for cases when there are more than 300 meetings already scheduled.
|
||||
(accessToken) =>
|
||||
fetch("https://api.zoom.us/v2/users/me/meetings?type=scheduled&page_size=300", {
|
||||
method: "get",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
},
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then((responseBody) => {
|
||||
return responseBody.meetings.map((meeting: { start_time: string; duration: number }) => ({
|
||||
start: meeting.start_time,
|
||||
end: new Date(
|
||||
new Date(meeting.start_time).getTime() + meeting.duration * 60000
|
||||
).toISOString(),
|
||||
}));
|
||||
})
|
||||
)
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
/* Prevents booking failure when Zoom Token is expired */
|
||||
return [];
|
||||
});
|
||||
},
|
||||
createMeeting: (event: CalendarEvent) =>
|
||||
auth.getToken().then((accessToken) =>
|
||||
fetch("https://api.zoom.us/v2/users/me/meetings", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event)),
|
||||
}).then(handleErrorsJson)
|
||||
),
|
||||
deleteMeeting: (uid: string) =>
|
||||
auth.getToken().then((accessToken) =>
|
||||
fetch("https://api.zoom.us/v2/meetings/" + uid, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
},
|
||||
}).then(handleErrorsRaw)
|
||||
),
|
||||
updateMeeting: (uid: string, event: CalendarEvent) =>
|
||||
auth.getToken().then((accessToken: string) =>
|
||||
fetch("https://api.zoom.us/v2/meetings/" + uid, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event)),
|
||||
}).then(handleErrorsRaw)
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
export default ZoomVideoApiAdapter;
|
||||
Reference in new issue
Block a user