refactor: Break videoClient into two separate files in app-store and features (#23992)

* getVideoAdapters

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2025-10-10 07:11:46 -03:00
1 parent 3bcce02b92
commit dbe55f0804
24 files changed
+75 -67

No files matched your search

@@ -8,8 +8,8 @@ import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApi
import { appKeysSchema as calVideoKeysSchema } from "@calcom/app-store/dailyvideo/zod";
import { getLocationFromApp, MeetLocationType, MSTeamsLocationType } from "@calcom/app-store/locations";
import getApps from "@calcom/app-store/utils";
import { createMeeting, updateMeeting, deleteMeeting } from "@calcom/app-store/videoClient";
import { createEvent, updateEvent, deleteEvent } from "@calcom/features/calendars/lib/CalendarManager";
import { createMeeting, updateMeeting, deleteMeeting } from "@calcom/features/conferencing/lib/videoClient";
import CrmManager from "@calcom/features/crmManager/crmManager";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { getUid } from "@calcom/lib/CalEventParser";
@@ -10,7 +10,7 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { updateMeeting } from "@calcom/app-store/videoClient";
import { updateMeeting } from "@calcom/features/conferencing/lib/videoClient";
import prisma from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { bookingCancelAttendeeSeatSchema } from "@calcom/prisma/zod-utils";
@@ -2,7 +2,7 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { getAllDelegationCredentialsForUserIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/app-store/delegationCredential";
import { deleteMeeting } from "@calcom/app-store/videoClient";
import { deleteMeeting } from "@calcom/features/conferencing/lib/videoClient";
import prisma from "@calcom/prisma";
import type { Attendee } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
+1 -1
View File
@@ -1,3 +1,3 @@
# Conferencing related code will live here
- [ ] Maybe migrate `videoClient` here
- [x] Maybe migrate `videoClient` here
@@ -0,0 +1,404 @@
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { DailyLocationType } from "@calcom/app-store/constants";
import { getDailyAppKeys } from "@calcom/app-store/dailyvideo/lib/getDailyAppKeys";
import { getVideoAdapters } from "@calcom/app-store/getVideoAdapters";
import { sendBrokenIntegrationEmail } from "@calcom/emails";
import { getUid } from "@calcom/lib/CalEventParser";
import logger from "@calcom/lib/logger";
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { prisma } from "@calcom/prisma";
import type { GetRecordingsResponseSchema, GetAccessLinkResponseSchema } from "@calcom/prisma/zod-utils";
import type { CalendarEvent, EventBusyDate } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
import type { VideoCallData } from "@calcom/types/VideoApiAdapter";
const log = logger.getSubLogger({ prefix: ["[features/conferencing/lib] videoClient"] });
const translator = short();
const getBusyVideoTimes = async (withCredentials: CredentialPayload[]) =>
Promise.all((await getVideoAdapters(withCredentials)).map((c) => c?.getAvailability())).then((results) =>
results.reduce((acc, availability) => acc.concat(availability), [] as (EventBusyDate | undefined)[])
);
const createMeeting = async (credential: CredentialPayload, calEvent: CalendarEvent) => {
const uid: string = getUid(calEvent);
log.debug(
"createMeeting",
safeStringify({
credential: getPiiFreeCredential(credential),
uid,
calEvent: getPiiFreeCalendarEvent(calEvent),
})
);
if (!credential || !credential.appId) {
throw new Error(
"Credentials must be set! Video platforms are optional, so this method shouldn't even be called when no video credentials are set."
);
}
const videoAdapters = await getVideoAdapters([credential]);
const [firstVideoAdapter] = videoAdapters;
let createdMeeting;
let returnObject: {
appName: string;
type: string;
uid: string;
originalEvent: CalendarEvent;
success: boolean;
createdEvent: VideoCallData | undefined;
credentialId: number;
} = {
appName: credential.appId || "",
type: credential.type,
uid,
originalEvent: calEvent,
success: false,
createdEvent: undefined,
credentialId: credential.id,
};
try {
// Check to see if video app is enabled
const enabledApp = await prisma.app.findUnique({
where: {
slug: credential.appId,
},
select: {
enabled: true,
},
});
if (!enabledApp?.enabled)
throw `Location app ${credential.appId} is either disabled or not seeded at all`;
createdMeeting = await firstVideoAdapter?.createMeeting(calEvent);
returnObject = { ...returnObject, createdEvent: createdMeeting, success: true };
log.debug("created Meeting", safeStringify(returnObject));
} catch (err) {
await sendBrokenIntegrationEmail(calEvent, "video");
log.error(
"createMeeting failed",
safeStringify(err),
safeStringify({ calEvent: getPiiFreeCalendarEvent(calEvent) })
);
// Default to calVideo
const defaultMeeting = await createMeetingWithCalVideo(calEvent);
if (defaultMeeting) {
calEvent.location = DailyLocationType;
}
returnObject = { ...returnObject, originalEvent: calEvent, createdEvent: defaultMeeting };
}
return returnObject;
};
const updateMeeting = async (
credential: CredentialPayload,
calEvent: CalendarEvent,
bookingRef: PartialReference | null
): Promise<EventResult<VideoCallData>> => {
const uid = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
let success = true;
const [firstVideoAdapter] = await getVideoAdapters([credential]);
const canCallUpdateMeeting = !!(credential && bookingRef);
const updatedMeeting = canCallUpdateMeeting
? await firstVideoAdapter?.updateMeeting(bookingRef, calEvent).catch(async (e) => {
await sendBrokenIntegrationEmail(calEvent, "video");
log.error("updateMeeting failed", e, calEvent);
success = false;
return undefined;
})
: undefined;
if (!updatedMeeting) {
log.error(
"updateMeeting failed",
safeStringify({ bookingRef, canCallUpdateMeeting, calEvent, credential })
);
return {
appName: credential.appId || "",
type: credential.type,
success,
uid,
originalEvent: calEvent,
};
}
return {
appName: credential.appId || "",
type: credential.type,
success,
uid,
updatedEvent: updatedMeeting,
originalEvent: calEvent,
};
};
const deleteMeeting = async (credential: CredentialPayload | null, uid: string): Promise<unknown> => {
if (credential) {
const videoAdapter = (await getVideoAdapters([credential]))[0];
log.debug(
"Calling deleteMeeting for",
safeStringify({ credential: getPiiFreeCredential(credential), uid })
);
// There are certain video apps with no video adapter defined. e.g. riverby,whereby
if (videoAdapter) {
return videoAdapter.deleteMeeting(uid);
}
}
return Promise.resolve({});
};
// @TODO: This is a temporary solution to create a meeting with cal.com video as fallback url
const createMeetingWithCalVideo = async (calEvent: CalendarEvent) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.createMeeting(calEvent);
};
export const createInstantMeetingWithCalVideo = async (endTime: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.createInstantCalVideoRoom?.(endTime);
};
const getRecordingsOfCalVideoByRoomName = async (
roomName: string
): Promise<GetRecordingsResponseSchema | undefined> => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getRecordings?.(roomName);
};
const getDownloadLinkOfCalVideoByRecordingId = async (
recordingId: string
): Promise<GetAccessLinkResponseSchema | undefined> => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getRecordingDownloadLink?.(recordingId);
};
const getAllTranscriptsAccessLinkFromRoomName = async (roomName: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getAllTranscriptsAccessLinkFromRoomName?.(roomName);
};
const getAllTranscriptsAccessLinkFromMeetingId = async (meetingId: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getAllTranscriptsAccessLinkFromMeetingId?.(meetingId);
};
const submitBatchProcessorTranscriptionJob = async (recordingId: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.submitBatchProcessorJob?.({
preset: "transcript",
inParams: {
sourceType: "recordingId",
recordingId: recordingId,
},
outParams: {
s3Config: {
s3KeyTemplate: "transcript",
},
},
});
};
const getTranscriptsAccessLinkFromRecordingId = async (recordingId: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.getTranscriptsAccessLinkFromRecordingId?.(recordingId);
};
const checkIfRoomNameMatchesInRecording = async (roomName: string, recordingId: string) => {
let dailyAppKeys: Awaited<ReturnType<typeof getDailyAppKeys>>;
try {
dailyAppKeys = await getDailyAppKeys();
} catch (e) {
console.error("Error: Cal video provider is not installed.");
return;
}
const [videoAdapter] = await getVideoAdapters([
{
id: 0,
appId: "daily-video",
type: "daily_video",
userId: null,
user: { email: "" },
teamId: null,
key: dailyAppKeys,
invalid: false,
delegationCredentialId: null,
},
]);
return videoAdapter?.checkIfRoomNameMatchesInRecording?.(roomName, recordingId);
};
export {
getBusyVideoTimes,
createMeeting,
updateMeeting,
deleteMeeting,
getRecordingsOfCalVideoByRoomName,
getDownloadLinkOfCalVideoByRecordingId,
getAllTranscriptsAccessLinkFromRoomName,
getAllTranscriptsAccessLinkFromMeetingId,
submitBatchProcessorTranscriptionJob,
getTranscriptsAccessLinkFromRecordingId,
checkIfRoomNameMatchesInRecording,
};
@@ -21,7 +21,7 @@ vi.mock("@calcom/features/notifications/sendNotification", () => ({
sendNotification: vi.fn(),
}));
vi.mock("@calcom/app-store/videoClient", () => ({
vi.mock("@calcom/features/conferencing/lib/videoClient", () => ({
createInstantMeetingWithCalVideo: vi.fn().mockResolvedValue({
type: "daily_video",
id: "MOCK_INSTANT_MEETING_ID",
@@ -2,7 +2,6 @@ import { randomBytes } from "crypto";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { createInstantMeetingWithCalVideo } from "@calcom/app-store/videoClient";
import dayjs from "@calcom/dayjs";
import type {
CreateInstantBookingData,
@@ -14,6 +13,7 @@ import { getBookingData } from "@calcom/features/bookings/lib/handleNewBooking/g
import { getCustomInputsResponses } from "@calcom/features/bookings/lib/handleNewBooking/getCustomInputsResponses";
import { getEventTypesFromDB } from "@calcom/features/bookings/lib/handleNewBooking/getEventTypesFromDB";
import type { IBookingCreateService } from "@calcom/features/bookings/lib/interfaces/IBookingCreateService";
import { createInstantMeetingWithCalVideo } from "@calcom/features/conferencing/lib/videoClient";
import { getFullName } from "@calcom/features/form-builder/utils";
import { sendNotification } from "@calcom/features/notifications/sendNotification";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";