App Store (#1869)
* patch applied * patch applied * We shouldn't pollute global css * Build fixes * Updates typings * WIP extracting zoom to package * Revert "Upgrades next to 12.1 (#1895)" (#1903) This reverts commitede0e98e1f. * Tweak/gitignore prisma zod (#1905) * Extracts ignored createEventTypeBaseInput * Adds postinstall script * Revert "Tweak/gitignore prisma zod (#1905)" (#1906) This reverts commit15bfeb30d7. * Eslint fixes (#1898) * Eslint fixes * Docs build fixes * Upgrade to next 12.1 (#1904) * Upgrades next to 12.1 * Fixes build * Updaters e2e test pipelines Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> * Fix URL by removing slash and backslash (#1733) * Fix URl by removing slash and backslash * Implement slugify * Add data type * Fixing folder structure * Solve zod-utils conflict * Build fixes (#1929) * Build fixes * Fixes type error * WIP * Conflict fixes * Removes unused file * TODO * WIP * Type fixes * Linting * WIP * Moved App definition to types * WIP * WIP * WIP * WIP WIP * Renamed zoomvideo app * Import fix * Daily.co app (#2022) * Daily.co app * Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts Co-authored-by: Omar López <[email protected]> * Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts Co-authored-by: Omar López <[email protected]> * Missing deps for newly added contants to lib Co-authored-by: Omar López <[email protected]> * WIP * WIP * WIP * Daily fixes * Updated type info * Slack Oauth integration - api route ideas * Adds getLocationOptions * Type fixes * Adds location option for daily video * Revert "Slack Oauth integration - api route ideas" This reverts commit 35ffa78e929339c4badb98cdab4e4b953ecc7cca. * Slack Oauth + verify sig * Revert "Slack Oauth + verify sig" This reverts commit ee95795e0f0ae6d06be4e0a423afb8c315d9af7d. * Huddle01 migration to app store (#2038) * Jitsi Video App migration * Removing uneeded dependencies * Missed unused reference * Missing dependency `@calcom/lib` is needed in the `locationOption.ts` file * Huddle01 migration to app store * Jitsi Video App migration (#2027) * Jitsi Video App migration * Removing uneeded dependencies * Missed unused reference * Missing dependency `@calcom/lib` is needed in the `locationOption.ts` file Co-authored-by: Omar López <[email protected]> * Monorepo/app store MS Teams Integration (#2080) * Create teamsvideo package * Remove zoom specific refrences * Add teams video files * Rename to office365_video * Add call back to add crednetial type office365_teams * Rename to office_video to match type * Add MS Teams as a location option * Rename files * Add teams reponse interface and create meeting * Comment out Daily imports * Add check for Teams integration * Add token checking functions * Change template to create event rather than meeting * Add comment to test between create link and event * Add teams URL to booking * Ask for just onlineMeeting permission * Add MS Teams logo * Add message to have an enterprise account * Remove comments * Comment back hasDailyIntegration * Comment back daily credentials * Update link to MS Graph section of README * Move API calls to package Co-authored-by: Omar López <[email protected]> * Re-adds missing module for transpiling * Adds email as required field for app store metadata * WIP: migrates tandem to app store * Cleanup * Migrates tandem api routes to app store * Fixes tandem api handlers * Big WIP WIP * Build fixes * WIP * Fixes annoying circular dependency bug I've spent a whole day on this.... * Location option cleanup * Type fixes * Update EventManager.ts * Update CalendarManager.ts * Moves CalendarService back to lib * Moves apple calendar to App Store * Cleanup * More cleanup * Migrates apple calendar * Returns all connected calendars credentials * No tsx needed in calcom/lib * Update auth.ts * Reordering * Update i18n.utils.ts * WIP: Google Meet * Type fixes * Type fixes * Cleanup * Update LinkIconButton.tsx * Update TrialBanner.tsx * Cleanup * Cleanup * Type fixes * Update _appRegistry.ts * Update fonts.css * Update CalEventParser.ts * Delete yarn.lock.rej * Update eslint-preset.js * Delete zoom.tsx * Type fixes * Migrates caldav to app store * Cleanup * Type fixes * Adds caldav to app store * Test fixes * Updates integration tests * Moar test fixes * Redirection fixes * Redirection fixes * Update timeFormat.ts * Update booking-pages.test.ts * Connect button fixes * Fix empty item * Cal fixes andrea (#2234) * Fixes #2178 * Fixes #2178 * Update apps/web/components/availability/Schedule.tsx * Update apps/web/components/availability/Schedule.tsx Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> * added meta viewport to disable zoom on input focus on mobile (#2238) * Update lint.yml (#2211) Co-authored-by: Peer Richelsen <[email protected]> * Fix prisma client bundle makes app slow (#2237) Co-authored-by: Omar López <[email protected]> * Slider fixes * Removed unused code * Full Shell when unauthed * App sidebar responsive fixes * Adds dynamic install button * Fix for duplicate connected calendars * Various fixes * Display notification on app delete * Reuse connect button * Adds CalDav button * Deprecates ConnectIntegration * Simplify install button * Adds Google Calendar connect button * Adds Office 365 Install button * Migrates Stripe to App Store * Zoom Install Button (#2244) * Fix minor css, app image load from static path * Fix app logos remote img src (#2252) * Adds missing exports * Cleanup * Disables install button for globally enabled apps * Update EventManager.ts * Stripe fixes * Disables example app Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Juan Esteban Nieto Cifuentes <[email protected]> Co-authored-by: Leo Giovanetti <[email protected]> Co-authored-by: Sean Brydon <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Bailey Pumfleet <[email protected]> Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: andreaestefania12 <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Demian Caldelas <[email protected]> Co-authored-by: Alan <[email protected]>
This commit is contained in:
242 files changed
+4322
-2260
No files matched your search
Vendored
-257
@@ -1,257 +0,0 @@
|
||||
// SPDX-FileCopyrightText: © 2019 EteSync Authors
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// https://github.com/mozilla-comm/ical.js/issues/367#issuecomment-568493517
|
||||
declare module "ical.js" {
|
||||
function parse(input: string): any[];
|
||||
|
||||
export class helpers {
|
||||
public updateTimezones(vcal: Component): Component;
|
||||
}
|
||||
|
||||
class Component {
|
||||
public fromString(str: string): Component;
|
||||
|
||||
public name: string;
|
||||
|
||||
constructor(jCal: any[] | string, parent?: Component);
|
||||
|
||||
public toJSON(): any[];
|
||||
|
||||
public getFirstSubcomponent(name?: string): Component | null;
|
||||
public getAllSubcomponents(name?: string): Component[];
|
||||
|
||||
public getFirstPropertyValue<T = any>(name?: string): T;
|
||||
|
||||
public getFirstProperty(name?: string): Property;
|
||||
public getAllProperties(name?: string): Property[];
|
||||
|
||||
public addProperty(property: Property): Property;
|
||||
public addPropertyWithValue(name: string, value: string | number | Record<string, unknown>): Property;
|
||||
|
||||
public hasProperty(name?: string): boolean;
|
||||
|
||||
public updatePropertyWithValue(name: string, value: string | number | Record<string, unknown>): Property;
|
||||
|
||||
public removeAllProperties(name?: string): boolean;
|
||||
|
||||
public addSubcomponent(component: Component): Component;
|
||||
}
|
||||
|
||||
export class Event {
|
||||
public uid: string;
|
||||
public summary: string;
|
||||
public startDate: Time;
|
||||
public endDate: Time;
|
||||
public description: string;
|
||||
public location: string;
|
||||
public attendees: Property[];
|
||||
/**
|
||||
* The sequence value for this event. Used for scheduling.
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof Event
|
||||
*/
|
||||
public sequence: number;
|
||||
/**
|
||||
* The duration. This can be the result directly from the property, or the
|
||||
* duration calculated from start date and end date. Setting the property
|
||||
* will remove any `dtend` properties.
|
||||
*
|
||||
* @type {Duration}
|
||||
* @memberof Event
|
||||
*/
|
||||
public duration: Duration;
|
||||
/**
|
||||
* The organizer value as an uri. In most cases this is a mailto: uri,
|
||||
* but it can also be something else, like urn:uuid:...
|
||||
*/
|
||||
public organizer: string;
|
||||
/** The sequence value for this event. Used for scheduling */
|
||||
public sequence: number;
|
||||
/** The recurrence id for this event */
|
||||
public recurrenceId: Time;
|
||||
|
||||
public component: Component;
|
||||
|
||||
public constructor(
|
||||
component?: Component | null,
|
||||
options?: { strictExceptions: boolean; exepctions: Array<Component | Event> }
|
||||
);
|
||||
|
||||
public isRecurring(): boolean;
|
||||
public iterator(startTime?: Time): RecurExpansion;
|
||||
}
|
||||
|
||||
export class Property {
|
||||
public name: string;
|
||||
public type: string;
|
||||
|
||||
constructor(jCal: any[] | string, parent?: Component);
|
||||
|
||||
public getFirstValue<T = any>(): T;
|
||||
public getValues<T = any>(): T[];
|
||||
|
||||
public setParameter(name: string, value: string | string[]): void;
|
||||
public setValue(value: string | Record<string, unknown>): void;
|
||||
public setValues(values: (string | Record<string, unknown>)[]): void;
|
||||
public toJSON(): any;
|
||||
}
|
||||
|
||||
interface TimeJsonData {
|
||||
year?: number;
|
||||
month?: number;
|
||||
day?: number;
|
||||
hour?: number;
|
||||
minute?: number;
|
||||
second?: number;
|
||||
isDate?: boolean;
|
||||
}
|
||||
|
||||
export class Time {
|
||||
public fromString(str: string): Time;
|
||||
public fromJSDate(aDate: Date | null, useUTC: boolean): Time;
|
||||
public fromData(aData: TimeJsonData): Time;
|
||||
|
||||
public now(): Time;
|
||||
|
||||
public isDate: boolean;
|
||||
public timezone: string;
|
||||
public zone: Timezone;
|
||||
|
||||
public year: number;
|
||||
public month: number;
|
||||
public day: number;
|
||||
public hour: number;
|
||||
public minute: number;
|
||||
public second: number;
|
||||
|
||||
constructor(data?: TimeJsonData);
|
||||
public compare(aOther: Time): number;
|
||||
|
||||
public clone(): Time;
|
||||
public convertToZone(zone: Timezone): Time;
|
||||
|
||||
public adjust(
|
||||
aExtraDays: number,
|
||||
aExtraHours: number,
|
||||
aExtraMinutes: number,
|
||||
aExtraSeconds: number,
|
||||
aTimeopt?: Time
|
||||
): void;
|
||||
|
||||
public addDuration(aDuration: Duration): void;
|
||||
public subtractDateTz(aDate: Time): Duration;
|
||||
|
||||
public toUnixTime(): number;
|
||||
public toJSDate(): Date;
|
||||
public toJSON(): TimeJsonData;
|
||||
public get icaltype(): "date" | "date-time";
|
||||
}
|
||||
|
||||
export class Duration {
|
||||
public weeks: number;
|
||||
public days: number;
|
||||
public hours: number;
|
||||
public minutes: number;
|
||||
public seconds: number;
|
||||
public isNegative: boolean;
|
||||
public icalclass: string;
|
||||
public icaltype: string;
|
||||
}
|
||||
|
||||
export class RecurExpansion {
|
||||
public complete: boolean;
|
||||
public dtstart: Time;
|
||||
public last: Time;
|
||||
public next(): Time;
|
||||
public fromData(options);
|
||||
public toJSON();
|
||||
constructor(options: {
|
||||
/** Start time of the event */
|
||||
dtstart: Time;
|
||||
/** Component for expansion, required if not resuming. */
|
||||
component?: Component;
|
||||
});
|
||||
}
|
||||
|
||||
export class Timezone {
|
||||
public utcTimezone: Timezone;
|
||||
public localTimezone: Timezone;
|
||||
public convert_time(tt: Time, fromZone: Timezone, toZone: Timezone): Time;
|
||||
|
||||
public tzid: string;
|
||||
public component: Component;
|
||||
|
||||
constructor(
|
||||
data:
|
||||
| Component
|
||||
| {
|
||||
component: string | Component;
|
||||
tzid?: string;
|
||||
location?: string;
|
||||
tznames?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export class TimezoneService {
|
||||
public get(tzid: string): Timezone | null;
|
||||
public has(tzid: string): boolean;
|
||||
public register(tzid: string, zone: Timezone | Component);
|
||||
public remove(tzid: string): Timezone | null;
|
||||
}
|
||||
|
||||
export type FrequencyValues =
|
||||
| "YEARLY"
|
||||
| "MONTHLY"
|
||||
| "WEEKLY"
|
||||
| "DAILY"
|
||||
| "HOURLY"
|
||||
| "MINUTELY"
|
||||
| "SECONDLY";
|
||||
|
||||
export enum WeekDay {
|
||||
SU = 1,
|
||||
MO,
|
||||
TU,
|
||||
WE,
|
||||
TH,
|
||||
FR,
|
||||
SA,
|
||||
}
|
||||
|
||||
export class RecurData {
|
||||
public freq?: FrequencyValues;
|
||||
public interval?: number;
|
||||
public wkst?: WeekDay;
|
||||
public until?: Time;
|
||||
public count?: number;
|
||||
public bysecond?: number[] | number;
|
||||
public byminute?: number[] | number;
|
||||
public byhour?: number[] | number;
|
||||
public byday?: string[] | string;
|
||||
public bymonthday?: number[] | number;
|
||||
public byyearday?: number[] | number;
|
||||
public byweekno?: number[] | number;
|
||||
public bymonth?: number[] | number;
|
||||
public bysetpos?: number[] | number;
|
||||
}
|
||||
|
||||
export class RecurIterator {
|
||||
public next(): Time;
|
||||
}
|
||||
|
||||
export class Recur {
|
||||
constructor(data?: RecurData);
|
||||
public until: Time | null;
|
||||
public freq: FrequencyValues;
|
||||
public count: number | null;
|
||||
|
||||
public clone(): Recur;
|
||||
public toJSON(): Omit<RecurData, "until"> & { until?: string };
|
||||
public iterator(startTime?: Time): RecurIterator;
|
||||
public isByCount(): boolean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import {
|
||||
BookOpenIcon,
|
||||
DocumentTextIcon,
|
||||
ExternalLinkIcon,
|
||||
FlagIcon,
|
||||
MailIcon,
|
||||
ShieldCheckIcon,
|
||||
} from "@heroicons/react/outline";
|
||||
import { ChevronLeftIcon } from "@heroicons/react/solid";
|
||||
import Link from "next/link";
|
||||
import React from "react";
|
||||
|
||||
import { InstallAppButton } from "@calcom/app-store/components";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { App as AppType } from "@calcom/types/App";
|
||||
import { Button } from "@calcom/ui";
|
||||
|
||||
//import NavTabs from "@components/NavTabs";
|
||||
import Shell from "@components/Shell";
|
||||
import Badge from "@components/ui/Badge";
|
||||
|
||||
export default function App({
|
||||
name,
|
||||
type,
|
||||
logo,
|
||||
body,
|
||||
categories,
|
||||
author,
|
||||
price = 0,
|
||||
commission,
|
||||
isGlobal = false,
|
||||
feeType,
|
||||
docs,
|
||||
website,
|
||||
email,
|
||||
tos,
|
||||
privacy,
|
||||
}: {
|
||||
name: string;
|
||||
type: AppType["type"];
|
||||
isGlobal?: AppType["isGlobal"];
|
||||
logo: string;
|
||||
body: React.ReactNode;
|
||||
categories: string[];
|
||||
author: string;
|
||||
pro?: boolean;
|
||||
price?: number;
|
||||
commission?: number;
|
||||
feeType?: AppType["feeType"];
|
||||
docs?: string;
|
||||
website?: string;
|
||||
email: string; // required
|
||||
tos?: string;
|
||||
privacy?: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
/*const tabs = [
|
||||
{
|
||||
name: t("description"),
|
||||
href: "?description",
|
||||
},
|
||||
{
|
||||
name: t("features"),
|
||||
href: "?features",
|
||||
},
|
||||
{
|
||||
name: t("permissions"),
|
||||
href: "?permissions",
|
||||
},
|
||||
];*/
|
||||
|
||||
const priceInDollar = Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
useGrouping: false,
|
||||
}).format(price);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Shell large>
|
||||
<div className="-mx-8">
|
||||
<div className="bg-gray-50 px-10">
|
||||
<Link href="/apps">
|
||||
<a className="mt-2 inline-flex px-1 py-2 text-sm text-gray-500 hover:bg-gray-100 hover:text-gray-800">
|
||||
<ChevronLeftIcon className="h-5 w-5" /> {t("browse_apps")}
|
||||
</a>
|
||||
</Link>
|
||||
<div className="flex items-center justify-between py-8">
|
||||
<div className="flex">
|
||||
<img className="h-16 w-16" src={logo} alt="" />
|
||||
<header className="px-4 py-2">
|
||||
<h1 className="font-cal text-xl text-gray-900">{name}</h1>
|
||||
<h2 className="text-sm text-gray-500">
|
||||
<span className="capitalize">{categories[0]}</span> • {t("published_by", { author })}
|
||||
</h2>
|
||||
</header>
|
||||
</div>
|
||||
|
||||
<div className="text-right">
|
||||
{isGlobal ? (
|
||||
<Button color="secondary" disabled title="This app is globally installed">
|
||||
{t("installed")}
|
||||
</Button>
|
||||
) : (
|
||||
<InstallAppButton
|
||||
type={type}
|
||||
render={(buttonProps) => <Button {...buttonProps}>{t("install_app")}</Button>}
|
||||
/>
|
||||
)}
|
||||
{price !== 0 && (
|
||||
<small className="block text-right">
|
||||
{feeType === "usage-based"
|
||||
? commission + "% + " + priceInDollar + "/booking"
|
||||
: priceInDollar}
|
||||
{feeType === "monthly" && "/" + t("month")}
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* reintroduce once we show permissions and features
|
||||
<NavTabs tabs={tabs} linkProps={{ shallow: true }} /> */}
|
||||
</div>
|
||||
|
||||
<div className="justify-between px-10 py-10 md:flex">
|
||||
<div className="prose-sm prose">{body}</div>
|
||||
<div className="md:max-w-80 flex-1 md:ml-8">
|
||||
<h4 className="font-medium text-gray-900 ">{t("categories")}</h4>
|
||||
<div className="space-x-2">
|
||||
{categories.map((category) => (
|
||||
<Link href={"/apps/categories/" + category} key={category}>
|
||||
<a>
|
||||
<Badge variant="success">{category}</Badge>
|
||||
</a>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<h4 className="mt-8 font-medium text-gray-900 ">{t("pricing")}</h4>
|
||||
<small>
|
||||
{price === 0 ? (
|
||||
"Free"
|
||||
) : (
|
||||
<>
|
||||
{Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
useGrouping: false,
|
||||
}).format(price)}
|
||||
{feeType === "monthly" && "/" + t("month")}
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
<h4 className="mt-8 mb-2 font-medium text-gray-900 ">{t("learn_more")}</h4>
|
||||
<ul className="prose -ml-1 -mr-1 text-xs leading-5">
|
||||
{docs && (
|
||||
<li>
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-blue-500 no-underline hover:underline"
|
||||
href={docs}>
|
||||
<BookOpenIcon className="mr-1 -mt-1 inline h-4 w-4" />
|
||||
{t("documentation")}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
{website && (
|
||||
<li>
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-blue-500 no-underline hover:underline"
|
||||
href={website}>
|
||||
<ExternalLinkIcon className="mr-1 -mt-px inline h-4 w-4" />
|
||||
{website.replace("https://", "")}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
{email && (
|
||||
<li>
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-blue-500 no-underline hover:underline"
|
||||
href={"mailto:" + email}>
|
||||
<MailIcon className="mr-1 -mt-px inline h-4 w-4" />
|
||||
{email}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
{tos && (
|
||||
<li>
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-blue-500 no-underline hover:underline"
|
||||
href={tos}>
|
||||
<DocumentTextIcon className="mr-1 -mt-px inline h-4 w-4" />
|
||||
{t("terms_of_service")}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
{privacy && (
|
||||
<li>
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-blue-500 no-underline hover:underline"
|
||||
href={privacy}>
|
||||
<ShieldCheckIcon className="mr-1 -mt-px inline h-4 w-4" />
|
||||
{t("privacy_policy")}
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
<hr className="my-6" />
|
||||
<small className="leading-1 block text-gray-500">
|
||||
Every app published on the Cal.com App Store is open source and thoroughly tested via peer
|
||||
reviews. Nevertheless, Cal.com, Inc. does not endorse or certify these apps unless they are
|
||||
published by Cal.com. If you encounter inappropriate content or behaviour please report it.
|
||||
</small>
|
||||
<a className="mt-2 block text-xs text-red-500" href="mailto:[email protected]">
|
||||
<FlagIcon className="inline h-3 w-3" /> Report App
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Shell>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import React from "react";
|
||||
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
|
||||
import NavTabs from "./NavTabs";
|
||||
|
||||
export default function AppsShell({ children }: { children: React.ReactNode }) {
|
||||
const { t } = useLocale();
|
||||
const { status } = useSession();
|
||||
const tabs = [
|
||||
{
|
||||
name: t("app_store"),
|
||||
href: "/apps",
|
||||
},
|
||||
{
|
||||
name: t("installed_apps"),
|
||||
href: "/apps/installed",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-12 block lg:hidden">
|
||||
{status === "authenticated" && <NavTabs tabs={tabs} linkProps={{ shallow: true }} />}
|
||||
</div>
|
||||
<main>{children}</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -67,7 +67,7 @@ const DestinationCalendarSelector = ({
|
||||
placeholder={!hidePlaceholder ? `${t("select_destination_calendar")}:` : undefined}
|
||||
options={options}
|
||||
isSearchable={false}
|
||||
className="focus:border-primary-500 focus:ring-primary-500 mt-1 mb-2 block w-full min-w-0 flex-1 rounded-none rounded-r-md border-gray-300 sm:text-sm"
|
||||
className="focus:ring-primary-500 focus:border-primary-500 mt-1 mb-2 block w-full min-w-0 flex-1 rounded-none rounded-r-md border-gray-300 sm:text-sm"
|
||||
onChange={(option) => {
|
||||
setSelectedOption(option);
|
||||
if (!option) {
|
||||
|
||||
+170
-116
@@ -1,20 +1,20 @@
|
||||
import { SelectorIcon } from "@heroicons/react/outline";
|
||||
import {
|
||||
CalendarIcon,
|
||||
ArrowLeftIcon,
|
||||
ClockIcon,
|
||||
CogIcon,
|
||||
ExternalLinkIcon,
|
||||
LinkIcon,
|
||||
LogoutIcon,
|
||||
PuzzleIcon,
|
||||
ViewGridIcon,
|
||||
MoonIcon,
|
||||
MapIcon,
|
||||
ArrowLeftIcon,
|
||||
} from "@heroicons/react/solid";
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { ReactNode, useEffect, useState } from "react";
|
||||
import React, { Fragment, ReactNode, useEffect, useState } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
|
||||
import Button from "@calcom/ui/Button";
|
||||
@@ -59,6 +59,10 @@ function useRedirectToLoginIfUnauthenticated() {
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (router.pathname.startsWith("/apps")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!loading && !session) {
|
||||
router.replace({
|
||||
pathname: "/auth/login",
|
||||
@@ -121,10 +125,11 @@ export function ShellSubHeading(props: {
|
||||
export default function Shell(props: {
|
||||
centered?: boolean;
|
||||
title?: string;
|
||||
heading: ReactNode;
|
||||
heading?: ReactNode;
|
||||
subtitle?: ReactNode;
|
||||
children: ReactNode;
|
||||
CTA?: ReactNode;
|
||||
large?: boolean;
|
||||
HeadingLeftIcon?: ReactNode;
|
||||
backPath?: string; // renders back button to specified path
|
||||
// use when content needs to expand with flex
|
||||
@@ -157,10 +162,22 @@ export default function Shell(props: {
|
||||
current: router.asPath.startsWith("/availability"),
|
||||
},
|
||||
{
|
||||
name: t("integrations"),
|
||||
href: "/integrations",
|
||||
icon: PuzzleIcon,
|
||||
current: router.asPath.startsWith("/integrations"),
|
||||
name: t("apps"),
|
||||
href: "/apps",
|
||||
icon: ViewGridIcon,
|
||||
current: router.asPath.startsWith("/apps"),
|
||||
child: [
|
||||
{
|
||||
name: t("app_store"),
|
||||
href: "/apps",
|
||||
current: router.asPath === "/apps",
|
||||
},
|
||||
{
|
||||
name: t("installed_apps"),
|
||||
href: "/apps/installed",
|
||||
current: router.asPath === "/apps/installed",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: t("settings"),
|
||||
@@ -182,6 +199,7 @@ export default function Shell(props: {
|
||||
const user = query.data;
|
||||
|
||||
const i18n = useViewerI18n();
|
||||
const { status } = useSession();
|
||||
|
||||
if (i18n.status === "loading" || isRedirectingToOnboarding || loading) {
|
||||
// show spinner whilst i18n is loading to avoid language flicker
|
||||
@@ -206,95 +224,121 @@ export default function Shell(props: {
|
||||
<Toaster position="bottom-right" />
|
||||
</div>
|
||||
|
||||
<div className="flex h-screen overflow-hidden bg-gray-100" data-testid="dashboard-shell">
|
||||
<div className="hidden md:flex lg:flex-shrink-0">
|
||||
<div className="flex w-14 flex-col lg:w-56">
|
||||
<div className="flex h-0 flex-1 flex-col border-r border-gray-200 bg-white">
|
||||
<div className="flex flex-1 flex-col overflow-y-auto pt-3 pb-4 lg:pt-5">
|
||||
<Link href="/event-types">
|
||||
<a className="px-4 md:hidden lg:inline">
|
||||
<Logo small />
|
||||
</a>
|
||||
</Link>
|
||||
{/* logo icon for tablet */}
|
||||
<Link href="/event-types">
|
||||
<a className="md:inline lg:hidden">
|
||||
<Logo small icon />
|
||||
</a>
|
||||
</Link>
|
||||
<nav className="mt-2 flex-1 space-y-1 bg-white px-2 lg:mt-5">
|
||||
{navigation.map((item) => (
|
||||
<Link key={item.name} href={item.href}>
|
||||
<a
|
||||
className={classNames(
|
||||
item.current
|
||||
? "bg-neutral-100 text-neutral-900"
|
||||
: "text-neutral-500 hover:bg-gray-50 hover:text-neutral-900",
|
||||
"group flex items-center rounded-sm px-2 py-2 text-sm font-medium"
|
||||
)}>
|
||||
<item.icon
|
||||
className={classNames(
|
||||
item.current
|
||||
? "text-neutral-500"
|
||||
: "text-neutral-400 group-hover:text-neutral-500",
|
||||
"h-5 w-5 flex-shrink-0 ltr:mr-3 rtl:ml-3"
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="hidden lg:inline">{item.name}</span>
|
||||
</a>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<div
|
||||
className={classNames("flex h-screen overflow-hidden", props.large ? "bg-white" : "bg-gray-100")}
|
||||
data-testid="dashboard-shell">
|
||||
{status === "authenticated" && (
|
||||
<div className="hidden md:flex lg:flex-shrink-0">
|
||||
<div className="flex w-14 flex-col lg:w-56">
|
||||
<div className="flex h-0 flex-1 flex-col border-r border-gray-200 bg-white">
|
||||
<div className="flex flex-1 flex-col overflow-y-auto pt-3 pb-4 lg:pt-5">
|
||||
<Link href="/event-types">
|
||||
<a className="px-4 md:hidden lg:inline">
|
||||
<Logo small />
|
||||
</a>
|
||||
</Link>
|
||||
{/* logo icon for tablet */}
|
||||
<Link href="/event-types">
|
||||
<a className="md:inline lg:hidden">
|
||||
<Logo small icon />
|
||||
</a>
|
||||
</Link>
|
||||
<nav className="mt-2 flex-1 space-y-1 bg-white px-2 lg:mt-5">
|
||||
{navigation.map((item) => (
|
||||
<Fragment key={item.name}>
|
||||
<Link href={item.href}>
|
||||
<a
|
||||
className={classNames(
|
||||
item.current
|
||||
? "bg-neutral-100 text-neutral-900"
|
||||
: "text-neutral-500 hover:bg-gray-50 hover:text-neutral-900",
|
||||
"group flex items-center rounded-sm px-2 py-2 text-sm font-medium"
|
||||
)}>
|
||||
<item.icon
|
||||
className={classNames(
|
||||
item.current
|
||||
? "text-neutral-500"
|
||||
: "text-neutral-400 group-hover:text-neutral-500",
|
||||
"h-5 w-5 flex-shrink-0 ltr:mr-3 rtl:ml-3"
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="hidden lg:inline">{item.name}</span>
|
||||
</a>
|
||||
</Link>
|
||||
{item.child &&
|
||||
router.asPath.startsWith(item.href) &&
|
||||
item.child.map((item) => {
|
||||
return (
|
||||
<Link key={item.name} href={item.href}>
|
||||
<a
|
||||
className={classNames(
|
||||
item.current
|
||||
? "text-neutral-900"
|
||||
: "text-neutral-500 hover:text-neutral-900",
|
||||
"group hidden items-center rounded-sm px-2 py-2 pl-10 text-sm font-medium lg:flex"
|
||||
)}>
|
||||
<span className="hidden lg:inline">{item.name}</span>
|
||||
</a>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</Fragment>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<TrialBanner />
|
||||
<div className="rounded-sm pb-2 pl-3 pt-2 pr-2 hover:bg-gray-100 lg:mx-2 lg:pl-2">
|
||||
<span className="hidden lg:inline">
|
||||
<UserDropdown />
|
||||
</span>
|
||||
<span className="hidden md:inline lg:hidden">
|
||||
<UserDropdown small />
|
||||
</span>
|
||||
</div>
|
||||
<small style={{ fontSize: "0.5rem" }} className="mx-3 mt-1 mb-2 hidden opacity-50 lg:block">
|
||||
© {new Date().getFullYear()} Cal.com, Inc. v.{pkg.version + "-"}
|
||||
{process.env.NEXT_PUBLIC_APP_URL === "https://cal.com" ? "h" : "sh"}
|
||||
<span className="lowercase">-{user && user.plan}</span>
|
||||
</small>
|
||||
</div>
|
||||
<TrialBanner />
|
||||
<div className="rounded-sm pt-2 pb-2 pl-3 pr-2 hover:bg-gray-100 lg:mx-2 lg:pl-2">
|
||||
<span className="hidden lg:inline">
|
||||
<UserDropdown />
|
||||
</span>
|
||||
<span className="hidden md:inline lg:hidden">
|
||||
<UserDropdown small />
|
||||
</span>
|
||||
</div>
|
||||
<small style={{ fontSize: "0.5rem" }} className="mx-3 mt-1 mb-2 hidden opacity-50 lg:block">
|
||||
© {new Date().getFullYear()} Cal.com, Inc. v.{pkg.version + "-"}
|
||||
{process.env.NEXT_PUBLIC_APP_URL === "https://cal.com" ? "h" : "sh"}
|
||||
<span className="lowercase">-{user && user.plan}</span>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex w-0 flex-1 flex-col overflow-hidden">
|
||||
<main
|
||||
className={classNames(
|
||||
"relative z-0 max-w-[1700px] flex-1 overflow-y-auto focus:outline-none",
|
||||
"relative z-0 flex-1 overflow-y-auto focus:outline-none",
|
||||
status === "authenticated" && "max-w-[1700px]",
|
||||
props.flexChildrenContainer && "flex flex-col"
|
||||
)}>
|
||||
{/* show top navigation for md and smaller (tablet and phones) */}
|
||||
<nav className="flex items-center justify-between border-b border-gray-200 bg-white p-4 md:hidden">
|
||||
<Link href="/event-types">
|
||||
<a>
|
||||
<Logo />
|
||||
</a>
|
||||
</Link>
|
||||
<div className="flex items-center gap-3 self-center">
|
||||
<button className="rounded-full bg-white p-2 text-gray-400 hover:bg-gray-50 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2">
|
||||
<span className="sr-only">{t("view_notifications")}</span>
|
||||
<Link href="/settings/profile">
|
||||
<a>
|
||||
<CogIcon className="h-6 w-6" aria-hidden="true" />
|
||||
</a>
|
||||
</Link>
|
||||
</button>
|
||||
<UserDropdown small />
|
||||
</div>
|
||||
</nav>
|
||||
{status === "authenticated" && (
|
||||
<nav className="flex items-center justify-between border-b border-gray-200 bg-white p-4 md:hidden">
|
||||
<Link href="/event-types">
|
||||
<a>
|
||||
<Logo />
|
||||
</a>
|
||||
</Link>
|
||||
<div className="flex items-center gap-3 self-center">
|
||||
<button className="rounded-full bg-white p-2 text-gray-400 hover:bg-gray-50 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2">
|
||||
<span className="sr-only">{t("view_notifications")}</span>
|
||||
<Link href="/settings/profile">
|
||||
<a>
|
||||
<CogIcon className="h-6 w-6" aria-hidden="true" />
|
||||
</a>
|
||||
</Link>
|
||||
</button>
|
||||
<UserDropdown small />
|
||||
</div>
|
||||
</nav>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
props.centered && "mx-auto md:max-w-5xl",
|
||||
props.flexChildrenContainer && "flex flex-1 flex-col",
|
||||
"py-8"
|
||||
!props.large && "py-8"
|
||||
)}>
|
||||
{!!props.backPath && (
|
||||
<div className="mx-3 mb-8 sm:mx-8">
|
||||
@@ -306,14 +350,22 @@ export default function Shell(props: {
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="block justify-between px-4 sm:flex sm:px-6 md:px-8">
|
||||
{props.HeadingLeftIcon && <div className="ltr:mr-4">{props.HeadingLeftIcon}</div>}
|
||||
<div className="mb-8 w-full">
|
||||
<h1 className="font-cal mb-1 text-xl text-gray-900">{props.heading}</h1>
|
||||
<p className="text-sm text-neutral-500 ltr:mr-4 rtl:ml-4">{props.subtitle}</p>
|
||||
{props.heading && props.subtitle && (
|
||||
<div
|
||||
className={classNames(
|
||||
props.large && "bg-gray-100 py-8 lg:mb-8 lg:pt-16 lg:pb-7",
|
||||
"block min-h-[80px] justify-between px-4 sm:flex sm:px-6 md:px-8"
|
||||
)}>
|
||||
{props.HeadingLeftIcon && <div className="ltr:mr-4">{props.HeadingLeftIcon}</div>}
|
||||
<div className="mb-8 w-full">
|
||||
<h1 className="font-cal mb-1 text-xl font-bold capitalize tracking-wide text-gray-900">
|
||||
{props.heading}
|
||||
</h1>
|
||||
<p className="text-sm text-neutral-500 ltr:mr-4 rtl:ml-4">{props.subtitle}</p>
|
||||
</div>
|
||||
{props.CTA && <div className="mb-4 flex-shrink-0">{props.CTA}</div>}
|
||||
</div>
|
||||
<div className="mb-4 flex-shrink-0">{props.CTA}</div>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
"px-4 sm:px-6 md:px-8",
|
||||
@@ -322,34 +374,36 @@ export default function Shell(props: {
|
||||
{props.children}
|
||||
</div>
|
||||
{/* show bottom navigation for md and smaller (tablet and phones) */}
|
||||
<nav className="bottom-nav fixed bottom-0 z-30 flex w-full bg-white shadow md:hidden">
|
||||
{/* note(PeerRich): using flatMap instead of map to remove settings from bottom nav */}
|
||||
{navigation.flatMap((item, itemIdx) =>
|
||||
item.href === "/settings/profile" ? (
|
||||
[]
|
||||
) : (
|
||||
<Link key={item.name} href={item.href}>
|
||||
<a
|
||||
className={classNames(
|
||||
item.current ? "text-gray-900" : "text-neutral-400 hover:text-gray-700",
|
||||
itemIdx === 0 ? "rounded-l-lg" : "",
|
||||
itemIdx === navigation.length - 1 ? "rounded-r-lg" : "",
|
||||
"group relative min-w-0 flex-1 overflow-hidden bg-white py-2 px-2 text-center text-xs font-medium hover:bg-gray-50 focus:z-10 sm:text-sm"
|
||||
)}
|
||||
aria-current={item.current ? "page" : undefined}>
|
||||
<item.icon
|
||||
{status === "authenticated" && (
|
||||
<nav className="bottom-nav fixed bottom-0 z-30 flex w-full bg-white shadow md:hidden">
|
||||
{/* note(PeerRich): using flatMap instead of map to remove settings from bottom nav */}
|
||||
{navigation.flatMap((item, itemIdx) =>
|
||||
item.href === "/settings/profile" ? (
|
||||
[]
|
||||
) : (
|
||||
<Link key={item.name} href={item.href}>
|
||||
<a
|
||||
className={classNames(
|
||||
item.current ? "text-gray-900" : "text-gray-400 group-hover:text-gray-500",
|
||||
"mx-auto mb-1 block h-5 w-5 flex-shrink-0 text-center"
|
||||
item.current ? "text-gray-900" : "text-neutral-400 hover:text-gray-700",
|
||||
itemIdx === 0 ? "rounded-l-lg" : "",
|
||||
itemIdx === navigation.length - 1 ? "rounded-r-lg" : "",
|
||||
"group relative min-w-0 flex-1 overflow-hidden bg-white py-2 px-2 text-center text-xs font-medium hover:bg-gray-50 focus:z-10 sm:text-sm"
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="truncate">{item.name}</span>
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
)}
|
||||
</nav>
|
||||
aria-current={item.current ? "page" : undefined}>
|
||||
<item.icon
|
||||
className={classNames(
|
||||
item.current ? "text-gray-900" : "text-gray-400 group-hover:text-gray-500",
|
||||
"mx-auto mb-1 block h-5 w-5 flex-shrink-0 text-center"
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="truncate">{item.name}</span>
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
{/* add padding to content for mobile navigation*/}
|
||||
<div className="block pt-12 md:hidden" />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { App } from "@calcom/types/App";
|
||||
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
|
||||
import AppCard from "./AppCard";
|
||||
|
||||
export default function AllApps({ apps }: { apps: App[] }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="mb-16">
|
||||
<h2 className="mb-2 text-lg font-semibold text-gray-900">{t("all_apps")}</h2>
|
||||
<div className="grid-col-1 grid gap-3 md:grid-cols-3">
|
||||
{apps.map((app) => (
|
||||
<AppCard
|
||||
key={app.name}
|
||||
name={app.name}
|
||||
slug={app.slug}
|
||||
description={app.description}
|
||||
logo={app.logo}
|
||||
rating={app.rating}
|
||||
reviews={app.reviews}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { StarIcon } from "@heroicons/react/solid";
|
||||
import Link from "next/link";
|
||||
|
||||
import Button from "@calcom/ui/Button";
|
||||
|
||||
interface AppCardProps {
|
||||
logo: string;
|
||||
name: string;
|
||||
slug?: string;
|
||||
category?: string;
|
||||
description: string;
|
||||
rating: number;
|
||||
reviews?: number;
|
||||
}
|
||||
|
||||
export default function AppCard(props: AppCardProps) {
|
||||
return (
|
||||
<Link href={"/apps/" + props.slug}>
|
||||
<a className="block h-full rounded-sm border border-gray-300 p-5 hover:bg-neutral-50">
|
||||
<div className="flex">
|
||||
<img src={props.logo} alt={props.name + " Logo"} className="mb-4 h-12 w-12 rounded-sm" />
|
||||
<Button
|
||||
color="secondary"
|
||||
className="ml-auto flex self-start"
|
||||
onClick={() => {
|
||||
// TODO: Actually add the integration
|
||||
console.log("The magic is supposed to happen here");
|
||||
}}>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
<h3 className="font-medium">{props.name}</h3>
|
||||
<div className="flex text-sm text-gray-800">
|
||||
<span>{props.rating} stars</span> <StarIcon className="ml-1 mt-0.5 h-4 w-4 text-yellow-600" />
|
||||
<span className="pl-1 text-gray-500">{props.reviews} reviews</span>
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-gray-500">{props.description}</p>
|
||||
</a>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { CreditCardIcon } from "@heroicons/react/outline";
|
||||
import Link from "next/link";
|
||||
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
|
||||
export default function AppStoreCategories(props: any) {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<div className="mb-16">
|
||||
<h2 className="mb-2 text-lg font-semibold text-gray-900">{t("popular_categories")}</h2>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
{props.categories.map((category: any) => (
|
||||
<Link key={category.name} href={"/apps/categories/" + category.name}>
|
||||
<a className="flex rounded-sm bg-gray-100 px-6 py-4">
|
||||
<div className="mr-4 flex h-12 w-12 rounded-sm bg-white">
|
||||
<CreditCardIcon className="mx-auto h-6 w-6 self-center" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-medium capitalize">{category.name}</h3>
|
||||
<p className="text-sm text-gray-500">{category.count} apps</p>
|
||||
</div>
|
||||
</a>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Glide from "@glidejs/glide";
|
||||
import "@glidejs/glide/dist/css/glide.core.min.css";
|
||||
import "@glidejs/glide/dist/css/glide.theme.min.css";
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/solid";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { App } from "@calcom/types/App";
|
||||
|
||||
import useMediaQuery from "@lib/hooks/useMediaQuery";
|
||||
|
||||
import AppCard from "./AppCard";
|
||||
|
||||
const Slider = <T extends App>({ items }: { items: T[] }) => {
|
||||
const { t } = useLocale();
|
||||
const isMobile = useMediaQuery("(max-width: 767px)");
|
||||
const [size, setSize] = useState(3);
|
||||
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
setSize(1);
|
||||
} else {
|
||||
setSize(3);
|
||||
}
|
||||
}, [isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
const slider = new Glide(".glide", {
|
||||
type: "carousel",
|
||||
perView: size,
|
||||
});
|
||||
|
||||
slider.mount();
|
||||
|
||||
// @ts-ignore TODO: This method is missing in types
|
||||
return () => slider.destroy();
|
||||
}, [size]);
|
||||
|
||||
return (
|
||||
<div className="mb-16">
|
||||
<style jsx global>
|
||||
{`
|
||||
.glide__slide {
|
||||
height: auto !important;
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
<div className="glide">
|
||||
<div className="flex cursor-default">
|
||||
<div>
|
||||
<h2 className="mb-2 text-lg font-semibold text-gray-900">{t("trending_apps")}</h2>
|
||||
</div>
|
||||
<div className="glide__arrows ml-auto" data-glide-el="controls">
|
||||
<button data-glide-dir="<" className="mr-4">
|
||||
<ArrowLeftIcon className="h-5 w-5 text-gray-600 hover:text-black" />
|
||||
</button>
|
||||
<button data-glide-dir=">">
|
||||
<ArrowRightIcon className="h-5 w-5 text-gray-600 hover:text-black" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="glide__track" data-glide-el="track">
|
||||
<ul className="glide__slides">
|
||||
{items.map((app) => {
|
||||
return (
|
||||
app.trending && (
|
||||
<li key={app.name} className="glide__slide h-auto">
|
||||
<AppCard
|
||||
key={app.name}
|
||||
name={app.name}
|
||||
slug={app.slug}
|
||||
description={app.description}
|
||||
logo={app.logo}
|
||||
rating={app.rating}
|
||||
reviews={app.reviews}
|
||||
/>
|
||||
</li>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Slider;
|
||||
@@ -132,6 +132,7 @@ const BookingPage = ({ eventType, booking, profile }: BookingPageProps) => {
|
||||
const locationInfo = (type: LocationType) => locations.find((location) => location.type === type);
|
||||
|
||||
// TODO: Move to translations
|
||||
// Also TODO: Get these dynamically from App Store
|
||||
const locationLabels = {
|
||||
[LocationType.InPerson]: t("in_person_meeting"),
|
||||
[LocationType.Phone]: t("phone_call"),
|
||||
@@ -141,6 +142,7 @@ const BookingPage = ({ eventType, booking, profile }: BookingPageProps) => {
|
||||
[LocationType.Daily]: "Daily.co Video",
|
||||
[LocationType.Huddle01]: "Huddle01 Video",
|
||||
[LocationType.Tandem]: "Tandem Video",
|
||||
[LocationType.Teams]: "MS Teams",
|
||||
};
|
||||
const loggedInIsOwner = eventType?.users[0]?.name === session?.user?.name;
|
||||
const defaultValues = () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Fragment } from "react";
|
||||
import { Fragment } from "react";
|
||||
import { useMutation } from "react-query";
|
||||
|
||||
import { InstallAppButton } from "@calcom/app-store/components";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { Alert } from "@calcom/ui/Alert";
|
||||
import Button from "@calcom/ui/Button";
|
||||
@@ -14,7 +15,6 @@ import DestinationCalendarSelector from "@components/DestinationCalendarSelector
|
||||
import { List } from "@components/List";
|
||||
import { ShellSubHeading } from "@components/Shell";
|
||||
|
||||
import ConnectIntegration from "./ConnectIntegrations";
|
||||
import DisconnectIntegration from "./DisconnectIntegration";
|
||||
import IntegrationListItem from "./IntegrationListItem";
|
||||
import SubHeadingTitleWithConnections from "./SubHeadingTitleWithConnections";
|
||||
@@ -110,7 +110,8 @@ function ConnectedCalendarsList(props: Props) {
|
||||
<Fragment key={item.credentialId}>
|
||||
{item.calendars ? (
|
||||
<IntegrationListItem
|
||||
{...item.integration}
|
||||
title={item.integration.title}
|
||||
imageSrc={item.integration.imageSrc}
|
||||
description={item.primary?.externalId || "No external Id"}
|
||||
actions={
|
||||
<DisconnectIntegration
|
||||
@@ -127,8 +128,8 @@ function ConnectedCalendarsList(props: Props) {
|
||||
{item.calendars.map((cal) => (
|
||||
<CalendarSwitch
|
||||
key={cal.externalId}
|
||||
externalId={cal.externalId as string}
|
||||
title={cal.name as string}
|
||||
externalId={cal.externalId}
|
||||
title={cal.name || "Nameless calendar"}
|
||||
type={item.integration.type}
|
||||
defaultSelected={cal.isSelected}
|
||||
/>
|
||||
@@ -174,16 +175,18 @@ function CalendarList(props: Props) {
|
||||
{data.calendar.items.map((item) => (
|
||||
<IntegrationListItem
|
||||
key={item.title}
|
||||
{...item}
|
||||
title={item.title}
|
||||
imageSrc={item.imageSrc}
|
||||
description={item.description}
|
||||
actions={
|
||||
<ConnectIntegration
|
||||
<InstallAppButton
|
||||
type={item.type}
|
||||
render={(btnProps) => (
|
||||
<Button color="secondary" {...btnProps} data-testid="integration-connection-button">
|
||||
render={(buttonProps) => (
|
||||
<Button color="secondary" {...buttonProps}>
|
||||
{t("connect")}
|
||||
</Button>
|
||||
)}
|
||||
onOpenChange={() => props.onChanged()}
|
||||
onChanged={() => props.onChanged()}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -193,6 +196,7 @@ function CalendarList(props: Props) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CalendarListContainer(props: { heading?: false }) {
|
||||
const { t } = useLocale();
|
||||
const { heading = true } = props;
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { IntegrationOAuthCallbackState } from "pages/api/integrations/types";
|
||||
import { useState } from "react";
|
||||
import { useMutation } from "react-query";
|
||||
|
||||
import { ButtonBaseProps } from "@calcom/ui/Button";
|
||||
|
||||
import { NEXT_PUBLIC_BASE_URL } from "@lib/config/constants";
|
||||
import { AddAppleIntegrationModal } from "@lib/integrations/calendar/components/AddAppleIntegration";
|
||||
import { AddCalDavIntegrationModal } from "@lib/integrations/calendar/components/AddCalDavIntegration";
|
||||
|
||||
export default function ConnectIntegration(props: {
|
||||
type: string;
|
||||
render: (renderProps: ButtonBaseProps) => JSX.Element;
|
||||
onOpenChange: (isOpen: boolean) => unknown | Promise<unknown>;
|
||||
}) {
|
||||
const { type } = props;
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const mutation = useMutation(async () => {
|
||||
const state: IntegrationOAuthCallbackState = {
|
||||
returnTo: NEXT_PUBLIC_BASE_URL + location.pathname + location.search,
|
||||
};
|
||||
const stateStr = encodeURIComponent(JSON.stringify(state));
|
||||
const searchParams = `?state=${stateStr}`;
|
||||
const res = await fetch("/api/integrations/" + type.replace("_", "") + "/add" + searchParams);
|
||||
if (!res.ok) {
|
||||
throw new Error("Something went wrong");
|
||||
}
|
||||
const json = await res.json();
|
||||
window.location.href = json.url;
|
||||
setIsLoading(true);
|
||||
});
|
||||
const [isModalOpen, _setIsModalOpen] = useState(false);
|
||||
|
||||
const setIsModalOpen = (v: boolean) => {
|
||||
_setIsModalOpen(v);
|
||||
props.onOpenChange(v);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{props.render({
|
||||
onClick() {
|
||||
if (["caldav_calendar", "apple_calendar"].includes(type)) {
|
||||
// special handlers
|
||||
setIsModalOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
mutation.mutate();
|
||||
},
|
||||
loading: mutation.isLoading || isLoading,
|
||||
disabled: isModalOpen,
|
||||
})}
|
||||
{type === "caldav_calendar" && (
|
||||
<AddCalDavIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />
|
||||
)}
|
||||
|
||||
{type === "apple_calendar" && (
|
||||
<AddAppleIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation } from "react-query";
|
||||
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { ButtonBaseProps } from "@calcom/ui/Button";
|
||||
import { Dialog } from "@calcom/ui/Dialog";
|
||||
|
||||
@@ -25,12 +26,14 @@ export default function DisconnectIntegration(props: {
|
||||
if (!res.ok) {
|
||||
throw new Error("Something went wrong");
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
{
|
||||
async onSettled() {
|
||||
await props.onOpenChange(modalOpen);
|
||||
},
|
||||
onSuccess() {
|
||||
onSuccess(data) {
|
||||
showToast(data.message, "success");
|
||||
setModalOpen(false);
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Image from "next/image";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
import classNames from "@lib/classNames";
|
||||
@@ -6,7 +5,7 @@ import classNames from "@lib/classNames";
|
||||
import { ListItem, ListItemText, ListItemTitle } from "@components/List";
|
||||
|
||||
function IntegrationListItem(props: {
|
||||
imageSrc: string;
|
||||
imageSrc?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
actions?: ReactNode;
|
||||
@@ -15,7 +14,7 @@ function IntegrationListItem(props: {
|
||||
return (
|
||||
<ListItem expanded={!!props.children} className={classNames("flex-col")}>
|
||||
<div className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
|
||||
<Image width={40} height={40} src={`/${props.imageSrc}`} alt={props.title} />
|
||||
{props.imageSrc && <img className="h-10 w-10" src={props.imageSrc} alt={props.title} />}
|
||||
<div className="flex-grow truncate pl-2">
|
||||
<ListItemTitle component="h3">{props.title}</ListItemTitle>
|
||||
<ListItemText component="p">{props.description}</ListItemText>
|
||||
|
||||
@@ -16,7 +16,7 @@ export const DatePicker = ({ date, onDatesChange, className }: Props) => {
|
||||
return (
|
||||
<PrimitiveDatePicker
|
||||
className={classNames(
|
||||
"focus:border-primary-500 focus:ring-primary-500 rounded-sm border border-gray-300 p-1 pl-2 shadow-sm sm:text-sm",
|
||||
"focus:ring-primary-500 focus:border-primary-500 rounded-sm border border-gray-300 p-1 pl-2 shadow-sm sm:text-sm",
|
||||
className
|
||||
)}
|
||||
clearIcon={null}
|
||||
|
||||
@@ -43,7 +43,7 @@ export default function WebhookListContainer(props: WebhookListContainerType) {
|
||||
<ListItem className={classNames("flex-col")}>
|
||||
<div
|
||||
className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
|
||||
<Image width={40} height={40} src="/integrations/webhooks.svg" alt="Webhooks" />
|
||||
<Image width={40} height={40} src="/apps/webhooks.svg" alt="Webhooks" />
|
||||
<div className="flex-grow truncate pl-2">
|
||||
<ListItemTitle component="h3">Webhooks</ListItemTitle>
|
||||
<ListItemText component="p">{t("automation")}</ListItemText>
|
||||
|
||||
@@ -74,7 +74,7 @@ export default function TeamAvailabilityModal(props: Props) {
|
||||
]}
|
||||
isSearchable={false}
|
||||
classNamePrefix="react-select"
|
||||
className="react-select-container focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
|
||||
className="react-select-container focus:ring-primary-500 focus:border-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
|
||||
value={{ value: frequency, label: `${frequency} minutes` }}
|
||||
onChange={(newFrequency) => setFrequency(newFrequency?.value ?? 30)}
|
||||
/>
|
||||
|
||||
@@ -47,7 +47,7 @@ export default function TeamAvailabilityScreen(props: Props) {
|
||||
<Avatar
|
||||
imageSrc={getPlaceholderAvatar(member?.avatar, member?.name as string)}
|
||||
alt={member?.name || ""}
|
||||
className="min-h-10 min-w-10 mt-1 h-10 w-10 rounded-full"
|
||||
className="min-w-10 min-h-10 mt-1 h-10 w-10 rounded-full"
|
||||
/>
|
||||
<div className="ml-3 inline-block overflow-hidden pt-1">
|
||||
<span className="truncate text-lg font-bold text-neutral-700">{member?.name}</span>
|
||||
@@ -93,7 +93,7 @@ export default function TeamAvailabilityScreen(props: Props) {
|
||||
]}
|
||||
isSearchable={false}
|
||||
classNamePrefix="react-select"
|
||||
className="react-select-container focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
|
||||
className="react-select-container focus:ring-primary-500 focus:border-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
|
||||
value={{ value: frequency, label: `${frequency} minutes` }}
|
||||
onChange={(newFrequency) => setFrequency(newFrequency?.value ?? 30)}
|
||||
/>
|
||||
|
||||
@@ -94,7 +94,7 @@ const CryptoSection = (props: CryptoSectionProps) => {
|
||||
const verifyButton = useMemo(() => {
|
||||
return (
|
||||
<Button color="secondary" onClick={verifyWallet} type="button" id="hasToken" name="hasToken">
|
||||
<img className="mr-1 h-5" src="/integrations/metamask.svg" />
|
||||
<img className="mr-1 h-5" src="/apps/metamask.svg" />
|
||||
{t("verify_wallet")}
|
||||
</Button>
|
||||
);
|
||||
@@ -103,7 +103,7 @@ const CryptoSection = (props: CryptoSectionProps) => {
|
||||
const connectButton = useMemo(() => {
|
||||
return (
|
||||
<Button color="secondary" onClick={connectMetamask} type="button">
|
||||
<img className="mr-1 h-5" src="/integrations/metamask.svg" />
|
||||
<img className="mr-1 h-5" src="/apps/metamask.svg" />
|
||||
{t("connect_metamask")}
|
||||
</Button>
|
||||
);
|
||||
@@ -118,7 +118,7 @@ const CryptoSection = (props: CryptoSectionProps) => {
|
||||
await connectMetamask();
|
||||
await verifyWallet();
|
||||
}}>
|
||||
<img className="mr-1 h-5" src="/integrations/metamask.svg" />
|
||||
<img className="mr-1 h-5" src="/apps/metamask.svg" />
|
||||
{t("verify_wallet")}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -6,9 +6,9 @@ import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { createPaymentLink } from "@calcom/stripe/client";
|
||||
import stripe, { PaymentData } from "@calcom/stripe/server";
|
||||
import { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { sendAwaitingPaymentEmail, sendOrganizerPaymentRefundFailedEmail } from "@lib/emails/email-manager";
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
|
||||
export type PaymentInfo = {
|
||||
link?: string | null;
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
const client_id = process.env.STRIPE_CLIENT_ID;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
|
||||
if (!session) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get user
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user?.id,
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
const redirect_uri = encodeURI(BASE_URL + "/api/integrations/stripepayment/callback");
|
||||
const stripeConnectParams = {
|
||||
client_id,
|
||||
scope: "read_write",
|
||||
response_type: "code",
|
||||
"stripe_user[email]": user?.email,
|
||||
"stripe_user[first_name]": user?.name,
|
||||
redirect_uri,
|
||||
};
|
||||
const query = stringify(stripeConnectParams);
|
||||
/**
|
||||
* Choose Express or Standard Stripe accounts
|
||||
* @url https://stripe.com/docs/connect/accounts
|
||||
*/
|
||||
// const url = `https://connect.stripe.com/express/oauth/authorize?${query}`;
|
||||
const url = `https://connect.stripe.com/oauth/authorize?${query}`;
|
||||
|
||||
res.status(200).json({ url });
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
import stripe, { StripeData } from "@calcom/stripe/server";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { code, error, error_description } = req.query;
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
|
||||
if (!session?.user) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
const query = stringify({ error, error_description });
|
||||
res.redirect("/integrations?" + query);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await stripe.oauth.token({
|
||||
grant_type: "authorization_code",
|
||||
code: code.toString(),
|
||||
});
|
||||
|
||||
const data: StripeData = { ...response, default_currency: "" };
|
||||
if (response["stripe_user_id"]) {
|
||||
const account = await stripe.accounts.retrieve(response["stripe_user_id"]);
|
||||
data["default_currency"] = account.default_currency;
|
||||
}
|
||||
|
||||
await prisma.credential.create({
|
||||
data: {
|
||||
type: "stripe_payment",
|
||||
key: data as unknown as Prisma.InputJsonObject,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
res.redirect("/integrations");
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getStripeCustomerIdFromUserId } from "@calcom/stripe/customer";
|
||||
import stripe from "@calcom/stripe/server";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const customerId = await getStripeCustomerIdFromUserId(session.user.id);
|
||||
|
||||
if (!customerId) {
|
||||
res.status(500).json({ message: "Missing customer id" });
|
||||
return;
|
||||
}
|
||||
|
||||
const return_url = `${process.env.BASE_URL}/settings/billing`;
|
||||
const stripeSession = await stripe.billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url,
|
||||
});
|
||||
|
||||
res.redirect(302, stripeSession.url);
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,14 @@ import { buffer } from "micro";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Stripe from "stripe";
|
||||
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import prisma from "@calcom/prisma";
|
||||
import stripe from "@calcom/stripe/server";
|
||||
import { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { IS_PRODUCTION } from "@lib/config/constants";
|
||||
import { HttpError as HttpCode } from "@lib/core/http/error";
|
||||
import EventManager from "@lib/events/EventManager";
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { getTranslation } from "@server/lib/i18n";
|
||||
|
||||
@@ -138,6 +138,11 @@ const webhookHandlers: Record<string, WebhookHandler | undefined> = {
|
||||
"payment_intent.succeeded": handlePaymentSuccess,
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* We need to create a PaymentManager in `@calcom/core`
|
||||
* to prevent circular dependencies on App Store migration
|
||||
*/
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
try {
|
||||
if (req.method !== "POST") {
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
import { Person } from "ics";
|
||||
import short from "short-uuid";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import { getIntegrationName } from "@lib/integrations";
|
||||
|
||||
import { BASE_URL } from "./config/constants";
|
||||
import { CalendarEvent } from "./integrations/calendar/interfaces/Calendar";
|
||||
|
||||
const translator = short();
|
||||
|
||||
// The odd indentation in this file is necessary because otherwise the leading tabs will be applied into the event description.
|
||||
|
||||
export const getWhat = (calEvent: CalendarEvent) => {
|
||||
return `
|
||||
${calEvent.organizer.language.translate("what")}:
|
||||
${calEvent.type}
|
||||
`;
|
||||
};
|
||||
|
||||
export const getWhen = (calEvent: CalendarEvent) => {
|
||||
return `
|
||||
${calEvent.organizer.language.translate("invitee_timezone")}:
|
||||
${calEvent.attendees[0].timeZone}
|
||||
`;
|
||||
};
|
||||
|
||||
export const getWho = (calEvent: CalendarEvent) => {
|
||||
const attendees = calEvent.attendees
|
||||
.map((attendee) => {
|
||||
return `
|
||||
${attendee?.name || calEvent.organizer.language.translate("guest")}
|
||||
${attendee.email}
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const organizer = `
|
||||
${calEvent.organizer.name} - ${calEvent.organizer.language.translate("organizer")}
|
||||
${calEvent.organizer.email}
|
||||
`;
|
||||
|
||||
return `
|
||||
${calEvent.organizer.language.translate("who")}:
|
||||
${organizer + attendees}
|
||||
`;
|
||||
};
|
||||
|
||||
export const getAdditionalNotes = (calEvent: CalendarEvent) => {
|
||||
return `
|
||||
${calEvent.organizer.language.translate("additional_notes")}:
|
||||
${calEvent.description}
|
||||
`;
|
||||
};
|
||||
|
||||
export const getLocation = (calEvent: CalendarEvent) => {
|
||||
let providerName = calEvent.location ? getIntegrationName(calEvent.location) : "";
|
||||
|
||||
if (calEvent.location && calEvent.location.includes("integrations:")) {
|
||||
const location = calEvent.location.split(":")[1];
|
||||
providerName = location[0].toUpperCase() + location.slice(1);
|
||||
}
|
||||
|
||||
if (calEvent.videoCallData) {
|
||||
return calEvent.videoCallData.url;
|
||||
}
|
||||
|
||||
if (calEvent.additionInformation?.hangoutLink) {
|
||||
return calEvent.additionInformation.hangoutLink;
|
||||
}
|
||||
|
||||
return providerName || calEvent.location || "";
|
||||
};
|
||||
|
||||
export const getManageLink = (calEvent: CalendarEvent) => {
|
||||
return `
|
||||
${calEvent.organizer.language.translate("need_to_reschedule_or_cancel")}
|
||||
${getCancelLink(calEvent)}
|
||||
`;
|
||||
};
|
||||
|
||||
export const getUid = (calEvent: CalendarEvent): string => {
|
||||
return calEvent.uid ?? translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
||||
};
|
||||
|
||||
export const getCancelLink = (calEvent: CalendarEvent): string => {
|
||||
return BASE_URL + "/cancel/" + getUid(calEvent);
|
||||
};
|
||||
|
||||
export const getRichDescription = (calEvent: CalendarEvent, attendee?: Person) => {
|
||||
// Only the original attendee can make changes to the event
|
||||
// Guests cannot
|
||||
|
||||
if (attendee && attendee === calEvent.attendees[0]) {
|
||||
return `
|
||||
${getWhat(calEvent)}
|
||||
${getWhen(calEvent)}
|
||||
${getWho(calEvent)}
|
||||
${calEvent.organizer.language.translate("where")}:
|
||||
${getLocation(calEvent)}
|
||||
${getAdditionalNotes(calEvent)}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
return `
|
||||
${getWhat(calEvent)}
|
||||
${getWhen(calEvent)}
|
||||
${getWho(calEvent)}
|
||||
${calEvent.organizer.language.translate("where")}:
|
||||
${getLocation(calEvent)}
|
||||
${getAdditionalNotes(calEvent)}
|
||||
${getManageLink(calEvent)}
|
||||
`.trim();
|
||||
};
|
||||
@@ -1,6 +1,2 @@
|
||||
export const BASE_URL = process.env.BASE_URL || `https://${process.env.VERCEL_URL}`;
|
||||
export const WEBSITE_URL = process.env.NEXT_PUBLIC_APP_URL || "https://cal.com";
|
||||
export const IS_PRODUCTION = process.env.NODE_ENV === "production";
|
||||
export const TRIAL_LIMIT_DAYS = 14;
|
||||
export const HOSTED_CAL_FEATURES = process.env.HOSTED_CAL_FEATURES || BASE_URL === "https://app.cal.com";
|
||||
export const NEXT_PUBLIC_BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || `https://${process.env.VERCEL_URL}`;
|
||||
// TODO: Remove this file once everything is imported from `@calcom/lib`
|
||||
export * from "@calcom/lib/constants";
|
||||
@@ -1,42 +0,0 @@
|
||||
import crypto from "crypto";
|
||||
|
||||
const ALGORITHM = "aes256";
|
||||
const INPUT_ENCODING = "utf8";
|
||||
const OUTPUT_ENCODING = "hex";
|
||||
const IV_LENGTH = 16; // AES blocksize
|
||||
|
||||
/**
|
||||
*
|
||||
* @param text Value to be encrypted
|
||||
* @param key Key used to encrypt value must be 32 bytes for AES256 encryption algorithm
|
||||
*
|
||||
* @returns Encrypted value using key
|
||||
*/
|
||||
export const symmetricEncrypt = function (text: string, key: string) {
|
||||
const _key = Buffer.from(key, "latin1");
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, _key, iv);
|
||||
let ciphered = cipher.update(text, INPUT_ENCODING, OUTPUT_ENCODING);
|
||||
ciphered += cipher.final(OUTPUT_ENCODING);
|
||||
const ciphertext = iv.toString(OUTPUT_ENCODING) + ":" + ciphered;
|
||||
|
||||
return ciphertext;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param text Value to decrypt
|
||||
* @param key Key used to decrypt value must be 32 bytes for AES256 encryption algorithm
|
||||
*/
|
||||
export const symmetricDecrypt = function (text: string, key: string) {
|
||||
const _key = Buffer.from(key, "latin1");
|
||||
|
||||
const components = text.split(":");
|
||||
const iv_from_ciphertext = Buffer.from(components.shift() || "", OUTPUT_ENCODING);
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext);
|
||||
let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING);
|
||||
deciphered += decipher.final(INPUT_ENCODING);
|
||||
|
||||
return deciphered;
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
||||
|
||||
import AttendeeAwaitingPaymentEmail from "@lib/emails/templates/attendee-awaiting-payment-email";
|
||||
import AttendeeCancelledEmail from "@lib/emails/templates/attendee-cancelled-email";
|
||||
import AttendeeDeclinedEmail from "@lib/emails/templates/attendee-declined-email";
|
||||
@@ -12,7 +14,6 @@ import OrganizerRequestReminderEmail from "@lib/emails/templates/organizer-reque
|
||||
import OrganizerRescheduledEmail from "@lib/emails/templates/organizer-rescheduled-email";
|
||||
import OrganizerScheduledEmail from "@lib/emails/templates/organizer-scheduled-email";
|
||||
import TeamInviteEmail, { TeamInvite } from "@lib/emails/templates/team-invite-email";
|
||||
import { CalendarEvent, Person } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
|
||||
export const sendScheduledEmails = async (calEvent: CalendarEvent) => {
|
||||
const emailsToSend: Promise<unknown>[] = [];
|
||||
|
||||
@@ -4,7 +4,7 @@ import timezone from "dayjs/plugin/timezone";
|
||||
import toArray from "dayjs/plugin/toArray";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { getCancelLink } from "@lib/CalEventParser";
|
||||
import { getCancelLink } from "@calcom/lib/CalEventParser";
|
||||
|
||||
import AttendeeScheduledEmail from "./attendee-scheduled-email";
|
||||
import {
|
||||
|
||||
@@ -6,11 +6,11 @@ import utc from "dayjs/plugin/utc";
|
||||
import { createEvent, DateArray } from "ics";
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
import { getAppName } from "@calcom/app-store/utils";
|
||||
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import type { Person, CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { getCancelLink, getRichDescription } from "@lib/CalEventParser";
|
||||
import { getIntegrationName } from "@lib/integrations";
|
||||
import { CalendarEvent, Person } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import { serverConfig } from "@lib/serverConfig";
|
||||
|
||||
import {
|
||||
@@ -309,7 +309,7 @@ ${getRichDescription(this.calEvent)}
|
||||
}
|
||||
|
||||
protected getLocation(): string {
|
||||
let providerName = this.calEvent.location ? getIntegrationName(this.calEvent.location) : "";
|
||||
let providerName = this.calEvent.location ? getAppName(this.calEvent.location) : "";
|
||||
|
||||
if (this.calEvent.location && this.calEvent.location.includes("integrations:")) {
|
||||
const location = this.calEvent.location.split(":")[1];
|
||||
|
||||
@@ -4,7 +4,7 @@ import timezone from "dayjs/plugin/timezone";
|
||||
import toArray from "dayjs/plugin/toArray";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { getCancelLink } from "@lib/CalEventParser";
|
||||
import { getCancelLink } from "@calcom/lib/CalEventParser";
|
||||
|
||||
import {
|
||||
emailHead,
|
||||
|
||||
@@ -6,11 +6,11 @@ import utc from "dayjs/plugin/utc";
|
||||
import { createEvent, DateArray, Person } from "ics";
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
import { getAppName } from "@calcom/app-store/utils";
|
||||
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { getCancelLink, getRichDescription } from "@lib/CalEventParser";
|
||||
import { getIntegrationName } from "@lib/integrations";
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import { serverConfig } from "@lib/serverConfig";
|
||||
|
||||
import {
|
||||
@@ -300,7 +300,7 @@ ${getRichDescription(this.calEvent)}
|
||||
}
|
||||
|
||||
protected getLocation(): string {
|
||||
let providerName = this.calEvent.location ? getIntegrationName(this.calEvent.location) : "";
|
||||
let providerName = this.calEvent.location ? getAppName(this.calEvent.location) : "";
|
||||
|
||||
if (this.calEvent.location && this.calEvent.location.includes("integrations:")) {
|
||||
const location = this.calEvent.location.split(":")[1];
|
||||
|
||||
@@ -1,364 +0,0 @@
|
||||
import { Credential, DestinationCalendar } from "@prisma/client";
|
||||
import async from "async";
|
||||
import merge from "lodash/merge";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import { FAKE_DAILY_CREDENTIAL } from "@lib/integrations/Daily/DailyVideoApiAdapter";
|
||||
import { FAKE_HUDDLE_CREDENTIAL } from "@lib/integrations/Huddle01/Huddle01VideoApiAdapter";
|
||||
import { FAKE_JITSI_CREDENTIAL } from "@lib/integrations/Jitsi/JitsiVideoApiAdapter";
|
||||
import { createEvent, updateEvent } from "@lib/integrations/calendar/CalendarManager";
|
||||
import { AdditionInformation, CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import { LocationType } from "@lib/location";
|
||||
import prisma from "@lib/prisma";
|
||||
import { createMeeting, updateMeeting, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
export type Event = AdditionInformation & VideoCallData;
|
||||
|
||||
export interface EventResult {
|
||||
type: string;
|
||||
success: boolean;
|
||||
uid: string;
|
||||
createdEvent?: Event;
|
||||
updatedEvent?: Event | Event[];
|
||||
originalEvent: CalendarEvent;
|
||||
}
|
||||
|
||||
export interface CreateUpdateResult {
|
||||
results: Array<EventResult>;
|
||||
referencesToCreate: Array<PartialReference>;
|
||||
}
|
||||
|
||||
export interface PartialBooking {
|
||||
id: number;
|
||||
references: Array<PartialReference>;
|
||||
}
|
||||
|
||||
export interface PartialReference {
|
||||
id?: number;
|
||||
type: string;
|
||||
uid: string;
|
||||
meetingId?: string | null;
|
||||
meetingPassword?: string | null;
|
||||
meetingUrl?: string | null;
|
||||
}
|
||||
|
||||
export const isZoom = (location: string): boolean => {
|
||||
return location === "integrations:zoom";
|
||||
};
|
||||
|
||||
export const isDaily = (location: string): boolean => {
|
||||
return location === "integrations:daily";
|
||||
};
|
||||
|
||||
export const isHuddle01 = (location: string): boolean => {
|
||||
return location === "integrations:huddle01";
|
||||
};
|
||||
|
||||
export const isTandem = (location: string): boolean => {
|
||||
return location === "integrations:tandem";
|
||||
};
|
||||
|
||||
export const isJitsi = (location: string): boolean => {
|
||||
return location === "integrations:jitsi";
|
||||
};
|
||||
|
||||
export const isDedicatedIntegration = (location: string): boolean => {
|
||||
return (
|
||||
isZoom(location) || isDaily(location) || isHuddle01(location) || isTandem(location) || isJitsi(location)
|
||||
);
|
||||
};
|
||||
|
||||
export const getLocationRequestFromIntegration = (location: string) => {
|
||||
if (
|
||||
location === LocationType.GoogleMeet.valueOf() ||
|
||||
location === LocationType.Zoom.valueOf() ||
|
||||
location === LocationType.Daily.valueOf() ||
|
||||
location === LocationType.Jitsi.valueOf() ||
|
||||
location === LocationType.Huddle01.valueOf() ||
|
||||
location === LocationType.Tandem.valueOf()
|
||||
) {
|
||||
const requestId = uuidv5(location, uuidv5.URL);
|
||||
|
||||
return {
|
||||
conferenceData: {
|
||||
createRequest: {
|
||||
requestId: requestId,
|
||||
},
|
||||
},
|
||||
location,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const processLocation = (event: CalendarEvent): CalendarEvent => {
|
||||
// If location is set to an integration location
|
||||
// Build proper transforms for evt object
|
||||
// Extend evt object with those transformations
|
||||
if (event.location?.includes("integration")) {
|
||||
const maybeLocationRequestObject = getLocationRequestFromIntegration(event.location);
|
||||
|
||||
event = merge(event, maybeLocationRequestObject);
|
||||
}
|
||||
|
||||
return event;
|
||||
};
|
||||
|
||||
type EventManagerUser = {
|
||||
credentials: Credential[];
|
||||
destinationCalendar: DestinationCalendar | null;
|
||||
};
|
||||
export default class EventManager {
|
||||
calendarCredentials: Credential[];
|
||||
videoCredentials: Credential[];
|
||||
|
||||
/**
|
||||
* Takes an array of credentials and initializes a new instance of the EventManager.
|
||||
*
|
||||
* @param credentials
|
||||
*/
|
||||
constructor(user: EventManagerUser) {
|
||||
this.calendarCredentials = user.credentials.filter((cred) => cred.type.endsWith("_calendar"));
|
||||
this.videoCredentials = user.credentials.filter((cred) => cred.type.endsWith("_video"));
|
||||
|
||||
//for Daily.co video, temporarily pushes a credential for the daily-video-client
|
||||
const hasDailyIntegration = process.env.DAILY_API_KEY;
|
||||
if (hasDailyIntegration) {
|
||||
this.videoCredentials.push(FAKE_DAILY_CREDENTIAL);
|
||||
}
|
||||
this.videoCredentials.push(FAKE_HUDDLE_CREDENTIAL);
|
||||
this.videoCredentials.push(FAKE_JITSI_CREDENTIAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a CalendarEvent and creates all necessary integration entries for it.
|
||||
* When a video integration is chosen as the event's location, a video integration
|
||||
* event will be scheduled for it as well.
|
||||
*
|
||||
* @param event
|
||||
*/
|
||||
public async create(event: CalendarEvent): Promise<CreateUpdateResult> {
|
||||
const evt = processLocation(event);
|
||||
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
|
||||
|
||||
const results: Array<EventResult> = [];
|
||||
// If and only if event type is a dedicated meeting, create a dedicated video meeting.
|
||||
if (isDedicated) {
|
||||
const result = await this.createVideoEvent(evt);
|
||||
if (result.createdEvent) {
|
||||
evt.videoCallData = result.createdEvent;
|
||||
}
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Create the calendar event with the proper video call data
|
||||
results.push(...(await this.createAllCalendarEvents(evt)));
|
||||
|
||||
const referencesToCreate: Array<PartialReference> = results.map((result: EventResult) => {
|
||||
return {
|
||||
type: result.type,
|
||||
uid: result.createdEvent?.id.toString() ?? "",
|
||||
meetingId: result.createdEvent?.id.toString(),
|
||||
meetingPassword: result.createdEvent?.password,
|
||||
meetingUrl: result.createdEvent?.url,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
results,
|
||||
referencesToCreate,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a calendarEvent and a rescheduleUid and updates the event that has the
|
||||
* given uid using the data delivered in the given CalendarEvent.
|
||||
*
|
||||
* @param event
|
||||
*/
|
||||
public async update(event: CalendarEvent, rescheduleUid: string): Promise<CreateUpdateResult> {
|
||||
const evt = processLocation(event);
|
||||
|
||||
if (!rescheduleUid) {
|
||||
throw new Error("You called eventManager.update without an `rescheduleUid`. This should never happen.");
|
||||
}
|
||||
|
||||
// Get details of existing booking.
|
||||
const booking = await prisma.booking.findFirst({
|
||||
where: {
|
||||
uid: rescheduleUid,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
references: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
uid: true,
|
||||
meetingId: true,
|
||||
meetingPassword: true,
|
||||
meetingUrl: true,
|
||||
},
|
||||
},
|
||||
destinationCalendar: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking) {
|
||||
throw new Error("booking not found");
|
||||
}
|
||||
|
||||
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
|
||||
const results: Array<EventResult> = [];
|
||||
// If and only if event type is a dedicated meeting, update the dedicated video meeting.
|
||||
if (isDedicated) {
|
||||
const result = await this.updateVideoEvent(evt, booking);
|
||||
const [updatedEvent] = Array.isArray(result.updatedEvent) ? result.updatedEvent : [result.updatedEvent];
|
||||
if (updatedEvent) {
|
||||
evt.videoCallData = updatedEvent;
|
||||
evt.location = updatedEvent.url;
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Update all calendar events.
|
||||
results.push(...(await this.updateAllCalendarEvents(evt, booking)));
|
||||
|
||||
// Now we can delete the old booking and its references.
|
||||
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
|
||||
where: {
|
||||
bookingId: booking.id,
|
||||
},
|
||||
});
|
||||
const attendeeDeletes = prisma.attendee.deleteMany({
|
||||
where: {
|
||||
bookingId: booking.id,
|
||||
},
|
||||
});
|
||||
|
||||
const bookingDeletes = prisma.booking.delete({
|
||||
where: {
|
||||
id: booking.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Wait for all deletions to be applied.
|
||||
await Promise.all([bookingReferenceDeletes, attendeeDeletes, bookingDeletes]);
|
||||
|
||||
return {
|
||||
results,
|
||||
referencesToCreate: [...booking.references],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates event entries for all calendar integrations given in the credentials.
|
||||
* When noMail is true, no mails will be sent. This is used when the event is
|
||||
* a video meeting because then the mail containing the video credentials will be
|
||||
* more important than the mails created for these bare calendar events.
|
||||
*
|
||||
* When the optional uid is set, it will be used instead of the auto generated uid.
|
||||
*
|
||||
* @param event
|
||||
* @param noMail
|
||||
* @private
|
||||
*/
|
||||
private async createAllCalendarEvents(event: CalendarEvent): Promise<Array<EventResult>> {
|
||||
/** Can I use destinationCalendar here? */
|
||||
/* How can I link a DC to a cred? */
|
||||
if (event.destinationCalendar) {
|
||||
const destinationCalendarCredentials = this.calendarCredentials.filter(
|
||||
(c) => c.type === event.destinationCalendar?.integration
|
||||
);
|
||||
return Promise.all(destinationCalendarCredentials.map(async (c) => await createEvent(c, event)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Not ideal but, if we don't find a destination calendar,
|
||||
* fallback to the first connected calendar
|
||||
*/
|
||||
const [credential] = this.calendarCredentials;
|
||||
if (!credential) {
|
||||
return [];
|
||||
}
|
||||
return [await createEvent(credential, event)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks which video integration is needed for the event's location and returns
|
||||
* credentials for that - if existing.
|
||||
* @param event
|
||||
* @private
|
||||
*/
|
||||
|
||||
private getVideoCredential(event: CalendarEvent): Credential | undefined {
|
||||
if (!event.location) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const integrationName = event.location.replace("integrations:", "");
|
||||
|
||||
return this.videoCredentials.find((credential: Credential) => credential.type.includes(integrationName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a video event entry for the selected integration location.
|
||||
*
|
||||
* When optional uid is set, it will be used instead of the auto generated uid.
|
||||
*
|
||||
* @param event
|
||||
* @private
|
||||
*/
|
||||
private createVideoEvent(event: CalendarEvent): Promise<EventResult> {
|
||||
const credential = this.getVideoCredential(event);
|
||||
|
||||
if (credential) {
|
||||
return createMeeting(credential, event);
|
||||
} else {
|
||||
return Promise.reject("No suitable credentials given for the requested integration name.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the event entries for all calendar integrations given in the credentials.
|
||||
* When noMail is true, no mails will be sent. This is used when the event is
|
||||
* a video meeting because then the mail containing the video credentials will be
|
||||
* more important than the mails created for these bare calendar events.
|
||||
*
|
||||
* @param event
|
||||
* @param booking
|
||||
* @private
|
||||
*/
|
||||
private updateAllCalendarEvents(
|
||||
event: CalendarEvent,
|
||||
booking: PartialBooking
|
||||
): Promise<Array<EventResult>> {
|
||||
return async.mapLimit(this.calendarCredentials, 5, async (credential: Credential) => {
|
||||
const bookingRefUid = booking
|
||||
? booking.references.filter((ref) => ref.type === credential.type)[0]?.uid
|
||||
: null;
|
||||
|
||||
return updateEvent(credential, event, bookingRefUid);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a single video event.
|
||||
*
|
||||
* @param event
|
||||
* @param booking
|
||||
* @private
|
||||
*/
|
||||
private updateVideoEvent(event: CalendarEvent, booking: PartialBooking) {
|
||||
const credential = this.getVideoCredential(event);
|
||||
|
||||
if (credential) {
|
||||
const bookingRef = booking ? booking.references.filter((ref) => ref.type === credential.type)[0] : null;
|
||||
return updateMeeting(credential, event, bookingRef);
|
||||
} else {
|
||||
return Promise.reject("No suitable credentials given for the requested integration name.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
const useMediaQuery = (query: string) => {
|
||||
const [matches, setMatches] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
if (media.matches !== matches) {
|
||||
setMatches(media.matches);
|
||||
}
|
||||
const listener = () => setMatches(media.matches);
|
||||
window.addEventListener("resize", listener);
|
||||
return () => window.removeEventListener("resize", listener);
|
||||
}, [matches, query]);
|
||||
|
||||
return matches;
|
||||
};
|
||||
|
||||
export default useMediaQuery;
|
||||
@@ -1,34 +0,0 @@
|
||||
export function getIntegrationName(name: string) {
|
||||
switch (name) {
|
||||
case "google_calendar":
|
||||
return "Google Calendar";
|
||||
case "office365_calendar":
|
||||
return "Office 365 Calendar";
|
||||
case "zoom_video":
|
||||
return "Zoom";
|
||||
case "caldav_calendar":
|
||||
return "CalDav Server";
|
||||
case "stripe_payment":
|
||||
return "Stripe";
|
||||
case "apple_calendar":
|
||||
return "Apple Calendar";
|
||||
case "daily_video":
|
||||
return "Daily";
|
||||
case "jitsi_video":
|
||||
return "Jitsi Meet";
|
||||
case "huddle01_video":
|
||||
return "Huddle01";
|
||||
case "tandem_video":
|
||||
return "Tandem";
|
||||
}
|
||||
}
|
||||
|
||||
export function getIntegrationType(name: string): string {
|
||||
if (name.endsWith("_calendar")) {
|
||||
return "Calendar";
|
||||
}
|
||||
if (name.endsWith("_payment")) {
|
||||
return "Payment";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { handleErrorsJson } from "@calcom/lib/errors";
|
||||
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import prisma from "@lib/prisma";
|
||||
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
import { CalendarEvent } from "../calendar/interfaces/Calendar";
|
||||
|
||||
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): Promise<VideoCallData> {
|
||||
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 Promise.resolve({
|
||||
type: "daily_video",
|
||||
id: dailyEvent.name,
|
||||
password: "",
|
||||
url: BASE_URL + "/video/" + event.uid,
|
||||
});
|
||||
}
|
||||
|
||||
const translateEvent = (event: CalendarEvent) => {
|
||||
// Documentation at: https://docs.daily.co/reference#list-rooms
|
||||
// added a 1 hour buffer for room expiration
|
||||
const exp = Math.round(new Date(event.endTime).getTime() / 1000) + 60 * 60;
|
||||
const scalePlan = process.env.DAILY_SCALE_PLAN;
|
||||
|
||||
if (scalePlan === "true") {
|
||||
return {
|
||||
privacy: "public",
|
||||
properties: {
|
||||
enable_new_call_ui: true,
|
||||
enable_prejoin_ui: true,
|
||||
enable_knocking: true,
|
||||
enable_screenshare: true,
|
||||
enable_chat: true,
|
||||
exp: exp,
|
||||
enable_recording: "local",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
privacy: "public",
|
||||
properties: {
|
||||
enable_new_call_ui: true,
|
||||
enable_prejoin_ui: true,
|
||||
enable_knocking: true,
|
||||
enable_screenshare: true,
|
||||
enable_chat: true,
|
||||
exp: exp,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
/** Daily doesn't need to return busy times, so we return empty */
|
||||
getAvailability: () => {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> =>
|
||||
createOrUpdateMeeting("/rooms", event),
|
||||
deleteMeeting: async (uid: string): Promise<void> => {
|
||||
await fetch("https://api.daily.co/v1/rooms/" + uid, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + dailyApiToken,
|
||||
},
|
||||
}).then(handleErrorsJson);
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
updateMeeting: (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> =>
|
||||
createOrUpdateMeeting("/rooms/" + bookingRef.uid, event),
|
||||
};
|
||||
};
|
||||
|
||||
export default DailyVideoApiAdapter;
|
||||
@@ -1,49 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { handleErrorsJson } from "@calcom/lib/errors";
|
||||
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import { randomString } from "@lib/random";
|
||||
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
export const FAKE_HUDDLE_CREDENTIAL: Credential = {
|
||||
id: +new Date().getTime(),
|
||||
type: "huddle01_video",
|
||||
key: { apikey: randomString(12) },
|
||||
userId: +new Date().getTime(),
|
||||
};
|
||||
|
||||
const Huddle01VideoApiAdapter = (): VideoApiAdapter => {
|
||||
return {
|
||||
getAvailability: () => {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
createMeeting: async (): Promise<VideoCallData> => {
|
||||
const res = await fetch(
|
||||
"https://wpss2zlpb9.execute-api.us-east-1.amazonaws.com/new-meeting?utmCampaign=cal.com&utmSource=partner&utmMedium=calendar"
|
||||
);
|
||||
|
||||
const { url } = await handleErrorsJson(res);
|
||||
|
||||
return Promise.resolve({
|
||||
type: "huddle01_video",
|
||||
id: randomString(21),
|
||||
password: "",
|
||||
url,
|
||||
});
|
||||
},
|
||||
deleteMeeting: async (): Promise<void> => {
|
||||
Promise.resolve();
|
||||
},
|
||||
updateMeeting: (bookingRef: PartialReference): Promise<VideoCallData> => {
|
||||
return Promise.resolve({
|
||||
type: "huddle01_video",
|
||||
id: bookingRef.meetingId as string,
|
||||
password: bookingRef.meetingPassword as string,
|
||||
url: bookingRef.meetingUrl as string,
|
||||
});
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default Huddle01VideoApiAdapter;
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import { randomString } from "@lib/random";
|
||||
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
export const FAKE_JITSI_CREDENTIAL: Credential = {
|
||||
id: +new Date().getTime(),
|
||||
type: "jitsi_video",
|
||||
key: { apikey: randomString(12) },
|
||||
userId: +new Date().getTime(),
|
||||
};
|
||||
|
||||
const JitsiVideoApiAdapter = (): VideoApiAdapter => {
|
||||
return {
|
||||
getAvailability: () => {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
createMeeting: async (): Promise<VideoCallData> => {
|
||||
const meetingID = uuidv4();
|
||||
return Promise.resolve({
|
||||
type: "jitsi_video",
|
||||
id: meetingID,
|
||||
password: "",
|
||||
url: "https://meet.jit.si/cal/" + meetingID,
|
||||
});
|
||||
},
|
||||
deleteMeeting: async (): Promise<void> => {
|
||||
Promise.resolve();
|
||||
},
|
||||
updateMeeting: (bookingRef: PartialReference): Promise<VideoCallData> => {
|
||||
return Promise.resolve({
|
||||
type: "jitsi_video",
|
||||
id: bookingRef.meetingId as string,
|
||||
password: bookingRef.meetingPassword as string,
|
||||
url: bookingRef.meetingUrl as string,
|
||||
});
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default JitsiVideoApiAdapter;
|
||||
@@ -1,144 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
|
||||
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import prisma from "@lib/prisma";
|
||||
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
import { CalendarEvent } from "../calendar/interfaces/Calendar";
|
||||
|
||||
interface TandemToken {
|
||||
expires_in?: number;
|
||||
expiry_date: number;
|
||||
refresh_token: string;
|
||||
token_type: "Bearer";
|
||||
access_token: string;
|
||||
}
|
||||
|
||||
const client_id = process.env.TANDEM_CLIENT_ID as string;
|
||||
const client_secret = process.env.TANDEM_CLIENT_SECRET as string;
|
||||
const TANDEM_BASE_URL = process.env.TANDEM_BASE_URL as string;
|
||||
|
||||
const tandemAuth = (credential: Credential) => {
|
||||
const credentialKey = credential.key as unknown as TandemToken;
|
||||
const isTokenValid = (token: TandemToken) => token && token.access_token && token.expiry_date < Date.now();
|
||||
|
||||
const refreshAccessToken = (refreshToken: string) => {
|
||||
fetch(`${TANDEM_BASE_URL}/api/v1/oauth/v2/token`, {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
client_id,
|
||||
client_secret,
|
||||
code: refreshToken,
|
||||
}),
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then(async (responseBody) => {
|
||||
// set expiry date as offset from current time.
|
||||
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
|
||||
delete responseBody.expires_in;
|
||||
// Store new tokens in database.
|
||||
await prisma.credential.update({
|
||||
where: {
|
||||
id: credential.id,
|
||||
},
|
||||
data: {
|
||||
key: responseBody,
|
||||
},
|
||||
});
|
||||
credentialKey.expiry_date = responseBody.expiry_date;
|
||||
credentialKey.access_token = responseBody.access_token;
|
||||
credentialKey.refresh_token = responseBody.refresh_token;
|
||||
return credentialKey.access_token;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
getToken: () =>
|
||||
!isTokenValid(credentialKey)
|
||||
? Promise.resolve(credentialKey.access_token)
|
||||
: refreshAccessToken(credentialKey.refresh_token),
|
||||
};
|
||||
};
|
||||
|
||||
const TandemVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
|
||||
const auth = tandemAuth(credential);
|
||||
|
||||
const _parseDate = (date: string) => {
|
||||
return Date.parse(date) / 1000;
|
||||
};
|
||||
|
||||
const _translateEvent = (event: CalendarEvent, param: string): string => {
|
||||
return JSON.stringify({
|
||||
[param]: {
|
||||
title: event.title,
|
||||
starts_at: _parseDate(event.startTime),
|
||||
ends_at: _parseDate(event.endTime),
|
||||
description: event.description || "",
|
||||
conference_solution: "tandem",
|
||||
type: 3,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const _translateResult = (result: { data: { id: string; event_link: string } }) => {
|
||||
return {
|
||||
type: "tandem_video",
|
||||
id: result.data.id as string,
|
||||
password: "",
|
||||
url: result.data.event_link,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
/** Tandem doesn't need to return busy times, so we return empty */
|
||||
getAvailability: () => {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
const result = await fetch(`${TANDEM_BASE_URL}/api/v1/meetings`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: _translateEvent(event, "meeting"),
|
||||
}).then(handleErrorsJson);
|
||||
|
||||
return Promise.resolve(_translateResult(result));
|
||||
},
|
||||
|
||||
deleteMeeting: async (uid: string): Promise<void> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
await fetch(`${TANDEM_BASE_URL}/api/v1/meetings/${uid}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
},
|
||||
}).then(handleErrorsRaw);
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
const result = await fetch(`${TANDEM_BASE_URL}/api/v1/meetings/${bookingRef.meetingId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: _translateEvent(event, "updates"),
|
||||
}).then(handleErrorsJson);
|
||||
|
||||
return Promise.resolve(_translateResult(result));
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default TandemVideoApiAdapter;
|
||||
@@ -1,233 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
|
||||
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import prisma from "@lib/prisma";
|
||||
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
|
||||
|
||||
import { CalendarEvent } from "../calendar/interfaces/Calendar";
|
||||
|
||||
/** @link https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate */
|
||||
export interface ZoomEventResult {
|
||||
password: string;
|
||||
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";
|
||||
expiry_date: number;
|
||||
expires_in?: number; // deprecated, purely for backwards compatibility; superseeded by expiry_date.
|
||||
token_type: "bearer";
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
const zoomAuth = (credential: Credential) => {
|
||||
const credentialKey = credential.key as unknown as ZoomToken;
|
||||
const isTokenValid = (token: ZoomToken) =>
|
||||
token && token.token_type && token.access_token && (token.expires_in || token.expiry_date) < Date.now();
|
||||
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) => {
|
||||
// set expiry date as offset from current time.
|
||||
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
|
||||
delete responseBody.expires_in;
|
||||
// Store new tokens in database.
|
||||
await prisma.credential.update({
|
||||
where: {
|
||||
id: credential.id,
|
||||
},
|
||||
data: {
|
||||
key: responseBody,
|
||||
},
|
||||
});
|
||||
credentialKey.expiry_date = responseBody.expiry_date;
|
||||
credentialKey.access_token = responseBody.access_token;
|
||||
return credentialKey.access_token;
|
||||
});
|
||||
|
||||
return {
|
||||
getToken: () =>
|
||||
!isTokenValid(credentialKey)
|
||||
? 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: async (event: CalendarEvent): Promise<VideoCallData> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
const result = await 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);
|
||||
|
||||
return Promise.resolve({
|
||||
type: "zoom_video",
|
||||
id: result.id as string,
|
||||
password: result.password ?? "",
|
||||
url: result.join_url,
|
||||
});
|
||||
},
|
||||
deleteMeeting: async (uid: string): Promise<void> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
await fetch("https://api.zoom.us/v2/meetings/" + uid, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
},
|
||||
}).then(handleErrorsRaw);
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
|
||||
const accessToken = await auth.getToken();
|
||||
|
||||
await fetch("https://api.zoom.us/v2/meetings/" + bookingRef.uid, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event)),
|
||||
}).then(handleErrorsRaw);
|
||||
|
||||
return Promise.resolve({
|
||||
type: "zoom_video",
|
||||
id: bookingRef.meetingId as string,
|
||||
password: bookingRef.meetingPassword as string,
|
||||
url: bookingRef.meetingUrl as string,
|
||||
});
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default ZoomVideoApiAdapter;
|
||||
@@ -1,181 +0,0 @@
|
||||
import { Credential, SelectedCalendar } from "@prisma/client";
|
||||
import _ from "lodash";
|
||||
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
|
||||
import { getUid } from "@lib/CalEventParser";
|
||||
import { EventResult } from "@lib/events/EventManager";
|
||||
import logger from "@lib/logger";
|
||||
import notEmpty from "@lib/notEmpty";
|
||||
|
||||
import { ALL_INTEGRATIONS } from "../getIntegrations";
|
||||
import { CALENDAR_INTEGRATIONS_TYPES } from "./constants/generals";
|
||||
import { CalendarServiceType, EventBusyDate } from "./constants/types";
|
||||
import { Calendar, CalendarEvent } from "./interfaces/Calendar";
|
||||
import AppleCalendarService from "./services/AppleCalendarService";
|
||||
import CalDavCalendarService from "./services/CalDavCalendarService";
|
||||
import GoogleCalendarService from "./services/GoogleCalendarService";
|
||||
import Office365CalendarService from "./services/Office365CalendarService";
|
||||
|
||||
const CALENDARS: Record<string, CalendarServiceType> = {
|
||||
[CALENDAR_INTEGRATIONS_TYPES.apple]: AppleCalendarService,
|
||||
[CALENDAR_INTEGRATIONS_TYPES.caldav]: CalDavCalendarService,
|
||||
[CALENDAR_INTEGRATIONS_TYPES.google]: GoogleCalendarService,
|
||||
[CALENDAR_INTEGRATIONS_TYPES.office365]: Office365CalendarService,
|
||||
};
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["CalendarManager"] });
|
||||
|
||||
export const getCalendar = (credential: Credential): Calendar | null => {
|
||||
const { type: calendarType } = credential;
|
||||
|
||||
const calendar = CALENDARS[calendarType];
|
||||
if (!calendar) {
|
||||
log.warn(`calendar of type ${calendarType} does not implemented`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return new calendar(credential);
|
||||
};
|
||||
|
||||
export const getCalendarCredentials = (credentials: Array<Omit<Credential, "userId">>, userId: number) => {
|
||||
const calendarCredentials = credentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
.flatMap((credential) => {
|
||||
const integration = ALL_INTEGRATIONS.find((integration) => integration.type === credential.type);
|
||||
|
||||
const calendar = getCalendar({
|
||||
...credential,
|
||||
userId,
|
||||
});
|
||||
return integration && calendar && integration.variant === "calendar"
|
||||
? [{ integration, credential, calendar }]
|
||||
: [];
|
||||
});
|
||||
|
||||
return calendarCredentials;
|
||||
};
|
||||
|
||||
export const getConnectedCalendars = async (
|
||||
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
|
||||
selectedCalendars: { externalId: string }[]
|
||||
) => {
|
||||
const connectedCalendars = await Promise.all(
|
||||
calendarCredentials.map(async (item) => {
|
||||
const { calendar, integration, credential } = item;
|
||||
|
||||
const credentialId = credential.id;
|
||||
try {
|
||||
const cals = await calendar.listCalendars();
|
||||
const calendars = _(cals)
|
||||
.map((cal) => ({
|
||||
...cal,
|
||||
primary: cal.primary || null,
|
||||
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
|
||||
}))
|
||||
.sortBy(["primary"])
|
||||
.value();
|
||||
const primary = calendars.find((item) => item.primary) ?? calendars[0];
|
||||
if (!primary) {
|
||||
throw new Error("No primary calendar found");
|
||||
}
|
||||
return {
|
||||
integration,
|
||||
credentialId,
|
||||
primary,
|
||||
calendars,
|
||||
};
|
||||
} catch (_error) {
|
||||
const error = getErrorFromUnknown(_error);
|
||||
return {
|
||||
integration,
|
||||
credentialId,
|
||||
error: {
|
||||
message: error.message,
|
||||
},
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return connectedCalendars;
|
||||
};
|
||||
|
||||
export const getBusyCalendarTimes = async (
|
||||
withCredentials: Credential[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[]
|
||||
) => {
|
||||
const calendars = withCredentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
.map((credential) => getCalendar(credential))
|
||||
.filter(notEmpty);
|
||||
|
||||
let results: EventBusyDate[][] = [];
|
||||
try {
|
||||
results = await Promise.all(calendars.map((c) => c.getAvailability(dateFrom, dateTo, selectedCalendars)));
|
||||
} catch (error) {
|
||||
log.warn(error);
|
||||
}
|
||||
|
||||
return results.reduce((acc, availability) => acc.concat(availability), []);
|
||||
};
|
||||
|
||||
export const createEvent = async (credential: Credential, calEvent: CalendarEvent): Promise<EventResult> => {
|
||||
const uid: string = getUid(calEvent);
|
||||
const calendar = getCalendar(credential);
|
||||
let success = true;
|
||||
|
||||
const creationResult = calendar
|
||||
? await calendar.createEvent(calEvent).catch((e) => {
|
||||
log.error("createEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
createdEvent: creationResult,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateEvent = async (
|
||||
credential: Credential,
|
||||
calEvent: CalendarEvent,
|
||||
bookingRefUid: string | null
|
||||
): Promise<EventResult> => {
|
||||
const uid = getUid(calEvent);
|
||||
const calendar = getCalendar(credential);
|
||||
let success = true;
|
||||
|
||||
const updatedResult =
|
||||
calendar && bookingRefUid
|
||||
? await calendar.updateEvent(bookingRefUid, calEvent).catch((e) => {
|
||||
log.error("updateEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
updatedEvent: updatedResult,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
};
|
||||
|
||||
export const deleteEvent = (credential: Credential, uid: string, event: CalendarEvent): Promise<unknown> => {
|
||||
const calendar = getCalendar(credential);
|
||||
if (calendar) {
|
||||
return calendar.deleteEvent(uid, event);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
@@ -1,102 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { Alert } from "@calcom/ui/Alert";
|
||||
import Button from "@calcom/ui/Button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogProps,
|
||||
} from "@calcom/ui/Dialog";
|
||||
import { Form, TextField } from "@calcom/ui/form/fields";
|
||||
|
||||
export const ADD_APPLE_INTEGRATION_FORM_TITLE = "addAppleIntegration";
|
||||
|
||||
export function AddAppleIntegrationModal(props: DialogProps) {
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
username: "",
|
||||
password: "",
|
||||
},
|
||||
});
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent>
|
||||
<DialogHeader
|
||||
title="Connect to Apple Server"
|
||||
subtitle={
|
||||
<>
|
||||
Generate an app specific password to use with Cal.com at{" "}
|
||||
<a
|
||||
className="text-indigo-400"
|
||||
href="https://appleid.apple.com/account/manage"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">
|
||||
https://appleid.apple.com/account/manage
|
||||
</a>
|
||||
. Your credentials will be stored and encrypted.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={async (values) => {
|
||||
setErrorMessage("");
|
||||
const res = await fetch("/api/integrations/apple/add", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(values),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
setErrorMessage(json?.message || "Something went wrong");
|
||||
} else {
|
||||
props.onOpenChange?.(false);
|
||||
}
|
||||
}}>
|
||||
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
|
||||
<TextField
|
||||
required
|
||||
type="text"
|
||||
{...form.register("username")}
|
||||
label="Username"
|
||||
placeholder="rickroll"
|
||||
/>
|
||||
<TextField
|
||||
required
|
||||
type="password"
|
||||
{...form.register("password")}
|
||||
label="Password"
|
||||
placeholder="•••••••••••••"
|
||||
autoComplete="password"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
|
||||
<DialogFooter>
|
||||
<DialogClose
|
||||
onClick={() => {
|
||||
props.onOpenChange?.(false);
|
||||
}}
|
||||
asChild>
|
||||
<Button type="button" color="secondary" tabIndex={-1}>
|
||||
Cancel
|
||||
</Button>
|
||||
</DialogClose>
|
||||
|
||||
<Button type="submit" loading={form.formState.isSubmitting}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import { Alert } from "@calcom/ui/Alert";
|
||||
import Button from "@calcom/ui/Button";
|
||||
import {
|
||||
DialogHeader,
|
||||
DialogProps,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogClose,
|
||||
DialogFooter,
|
||||
} from "@calcom/ui/Dialog";
|
||||
import { Form, TextField } from "@calcom/ui/form/fields";
|
||||
|
||||
type Props = {
|
||||
onSubmit: () => void;
|
||||
};
|
||||
|
||||
export const ADD_CALDAV_INTEGRATION_FORM_TITLE = "addCalDav";
|
||||
export type AddCalDavIntegrationRequest = {
|
||||
url: string;
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export function AddCalDavIntegrationModal(props: DialogProps) {
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
url: "",
|
||||
username: "",
|
||||
password: "",
|
||||
},
|
||||
});
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent>
|
||||
<DialogHeader
|
||||
title="Connect to CalDav Server"
|
||||
subtitle="Your credentials will be stored and encrypted."
|
||||
/>
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
handleSubmit={async (values) => {
|
||||
setErrorMessage("");
|
||||
const res = await fetch("/api/integrations/caldav/add", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(values),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
setErrorMessage(json?.message || "Something went wrong");
|
||||
} else {
|
||||
props.onOpenChange?.(false);
|
||||
}
|
||||
}}>
|
||||
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
|
||||
<TextField
|
||||
required
|
||||
type="text"
|
||||
{...form.register("url")}
|
||||
label="Calendar URL"
|
||||
placeholder="https://example.com/calendar"
|
||||
/>
|
||||
<TextField
|
||||
required
|
||||
type="text"
|
||||
{...form.register("username")}
|
||||
label="Username"
|
||||
placeholder="rickroll"
|
||||
/>
|
||||
<TextField
|
||||
required
|
||||
type="password"
|
||||
{...form.register("password")}
|
||||
label="Password"
|
||||
placeholder="•••••••••••••"
|
||||
autoComplete="password"
|
||||
/>
|
||||
</fieldset>
|
||||
|
||||
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
|
||||
<DialogFooter>
|
||||
<DialogClose
|
||||
onClick={() => {
|
||||
props.onOpenChange?.(false);
|
||||
}}
|
||||
asChild>
|
||||
<Button type="button" color="secondary" tabIndex={-1}>
|
||||
Cancel
|
||||
</Button>
|
||||
</DialogClose>
|
||||
|
||||
<Button type="submit" loading={form.formState.isSubmitting}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
const AddCalDavIntegration = React.forwardRef<HTMLFormElement, Props>((props, ref) => {
|
||||
const onSubmit = (event: any) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
props.onSubmit();
|
||||
};
|
||||
|
||||
return (
|
||||
<form id={ADD_CALDAV_INTEGRATION_FORM_TITLE} ref={ref} onSubmit={onSubmit}>
|
||||
<div className="mb-2">
|
||||
<label htmlFor="url" className="block text-sm font-medium text-gray-700">
|
||||
Calendar URL
|
||||
</label>
|
||||
<div className="mt-1 flex rounded-md shadow-sm">
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
name="url"
|
||||
id="url"
|
||||
placeholder="https://example.com/calendar"
|
||||
className="focus:border-brand block w-full min-w-0 flex-grow rounded-none rounded-r-sm border-gray-300 lowercase focus:ring-black sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<label htmlFor="username" className="block text-sm font-medium text-gray-700">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
name="username"
|
||||
id="username"
|
||||
placeholder="rickroll"
|
||||
className="mt-1 block w-full rounded-sm border border-gray-300 px-3 py-2 shadow-sm focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
name="password"
|
||||
id="password"
|
||||
placeholder="•••••••••••••"
|
||||
className="mt-1 block w-full rounded-sm border border-gray-300 px-3 py-2 shadow-sm focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
});
|
||||
|
||||
AddCalDavIntegration.displayName = "AddCalDavIntegrationForm";
|
||||
export default AddCalDavIntegration;
|
||||
@@ -1 +0,0 @@
|
||||
export const TIMEZONE_FORMAT = "YYYY-MM-DDTHH:mm:ss[Z]";
|
||||
@@ -1,10 +0,0 @@
|
||||
export const CALDAV_CALENDAR_TYPE = "caldav";
|
||||
|
||||
export const APPLE_CALENDAR_URL = "https://caldav.icloud.com";
|
||||
|
||||
export const CALENDAR_INTEGRATIONS_TYPES = {
|
||||
apple: "apple_calendar",
|
||||
caldav: "caldav_calendar",
|
||||
google: "google_calendar",
|
||||
office365: "office365_calendar",
|
||||
};
|
||||
@@ -1,57 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import ICAL from "ical.js";
|
||||
|
||||
import AppleCalendarService from "../services/AppleCalendarService";
|
||||
import CalDavCalendarService from "../services/CalDavCalendarService";
|
||||
import GoogleCalendarService from "../services/GoogleCalendarService";
|
||||
import Office365CalendarService from "../services/Office365CalendarService";
|
||||
|
||||
export type EventBusyDate = Record<"start" | "end", Date | string>;
|
||||
|
||||
export type CalendarServiceType =
|
||||
| typeof AppleCalendarService
|
||||
| typeof CalDavCalendarService
|
||||
| typeof GoogleCalendarService
|
||||
| typeof Office365CalendarService;
|
||||
|
||||
export type NewCalendarEventType = {
|
||||
uid: string;
|
||||
id: string;
|
||||
type: string;
|
||||
password: string;
|
||||
url: string;
|
||||
additionalInfo: Record<string, any>;
|
||||
};
|
||||
|
||||
export type CalendarEventType = {
|
||||
uid: string;
|
||||
etag: string;
|
||||
/** This is the actual caldav event url, not the location url. */
|
||||
url: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
location: string;
|
||||
sequence: number;
|
||||
startDate: Date | dayjs.Dayjs;
|
||||
endDate: Date | dayjs.Dayjs;
|
||||
duration: {
|
||||
weeks: number;
|
||||
days: number;
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
isNegative: boolean;
|
||||
};
|
||||
organizer: string;
|
||||
attendees: any[][];
|
||||
recurrenceId: ICAL.Time;
|
||||
timezone: any;
|
||||
};
|
||||
|
||||
export type BatchResponse = {
|
||||
responses: SubResponse[];
|
||||
};
|
||||
|
||||
export type SubResponse = {
|
||||
body: { value: { start: { dateTime: string }; end: { dateTime: string } }[] };
|
||||
};
|
||||
@@ -1,81 +0,0 @@
|
||||
import { DestinationCalendar, SelectedCalendar } from "@prisma/client";
|
||||
import { TFunction } from "next-i18next";
|
||||
|
||||
import { PaymentInfo } from "@ee/lib/stripe/server";
|
||||
|
||||
import type { Event } from "@lib/events/EventManager";
|
||||
import { Ensure } from "@lib/types/utils";
|
||||
import { VideoCallData } from "@lib/videoClient";
|
||||
|
||||
import { NewCalendarEventType } from "../constants/types";
|
||||
import { ConferenceData } from "./GoogleCalendar";
|
||||
|
||||
export type Person = {
|
||||
name: string;
|
||||
email: string;
|
||||
timeZone: string;
|
||||
language: { translate: TFunction; locale: string };
|
||||
};
|
||||
|
||||
export interface EntryPoint {
|
||||
entryPointType?: string;
|
||||
uri?: string;
|
||||
label?: string;
|
||||
pin?: string;
|
||||
accessCode?: string;
|
||||
meetingCode?: string;
|
||||
passcode?: string;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
export interface AdditionInformation {
|
||||
conferenceData?: ConferenceData;
|
||||
entryPoints?: EntryPoint[];
|
||||
hangoutLink?: string;
|
||||
}
|
||||
|
||||
export interface CalendarEvent {
|
||||
type: string;
|
||||
title: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
description?: string | null;
|
||||
team?: {
|
||||
name: string;
|
||||
members: string[];
|
||||
};
|
||||
location?: string | null;
|
||||
organizer: Person;
|
||||
attendees: Person[];
|
||||
conferenceData?: ConferenceData;
|
||||
additionInformation?: AdditionInformation;
|
||||
uid?: string | null;
|
||||
videoCallData?: VideoCallData;
|
||||
paymentInfo?: PaymentInfo | null;
|
||||
destinationCalendar?: DestinationCalendar | null;
|
||||
cancellationReason?: string | null;
|
||||
rejectionReason?: string | null;
|
||||
}
|
||||
|
||||
export interface IntegrationCalendar extends Ensure<Partial<SelectedCalendar>, "externalId"> {
|
||||
primary?: boolean;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
type EventBusyDate = Record<"start" | "end", Date | string>;
|
||||
|
||||
export interface Calendar {
|
||||
createEvent(event: CalendarEvent): Promise<NewCalendarEventType>;
|
||||
|
||||
updateEvent(uid: string, event: CalendarEvent): Promise<Event | Event[]>;
|
||||
|
||||
deleteEvent(uid: string, event: CalendarEvent): Promise<unknown>;
|
||||
|
||||
getAvailability(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: IntegrationCalendar[]
|
||||
): Promise<EventBusyDate[]>;
|
||||
|
||||
listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]>;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { calendar_v3 } from "googleapis";
|
||||
|
||||
export interface ConferenceData {
|
||||
createRequest?: calendar_v3.Schema$CreateConferenceRequest;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export type BufferedBusyTime = {
|
||||
start: string;
|
||||
end: string;
|
||||
};
|
||||
|
||||
export type O365AuthCredentials = {
|
||||
expiry_date: number;
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { APPLE_CALENDAR_URL, CALENDAR_INTEGRATIONS_TYPES } from "../constants/generals";
|
||||
import CalendarService from "./BaseCalendarService";
|
||||
|
||||
export default class AppleCalendarService extends CalendarService {
|
||||
constructor(credential: Credential) {
|
||||
super(credential, CALENDAR_INTEGRATIONS_TYPES.apple, APPLE_CALENDAR_URL);
|
||||
}
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
import { Credential, Prisma } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import ICAL from "ical.js";
|
||||
import { createEvent } from "ics";
|
||||
import {
|
||||
createAccount,
|
||||
createCalendarObject,
|
||||
DAVAccount,
|
||||
deleteCalendarObject,
|
||||
fetchCalendarObjects,
|
||||
fetchCalendars,
|
||||
getBasicAuthHeaders,
|
||||
updateCalendarObject,
|
||||
} from "tsdav";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { getLocation, getRichDescription } from "@lib/CalEventParser";
|
||||
import { symmetricDecrypt } from "@lib/crypto";
|
||||
import type { Event } from "@lib/events/EventManager";
|
||||
import logger from "@lib/logger";
|
||||
|
||||
import { TIMEZONE_FORMAT } from "../constants/formats";
|
||||
import { CALDAV_CALENDAR_TYPE } from "../constants/generals";
|
||||
import { CalendarEventType, EventBusyDate, NewCalendarEventType } from "../constants/types";
|
||||
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
|
||||
import { convertDate, getAttendees, getDuration } from "../utils/CalendarUtils";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
|
||||
|
||||
export default abstract class BaseCalendarService implements Calendar {
|
||||
private url = "";
|
||||
private credentials: Record<string, string> = {};
|
||||
private headers: Record<string, string> = {};
|
||||
protected integrationName = "";
|
||||
private log: typeof logger;
|
||||
|
||||
constructor(credential: Credential, integrationName: string, url?: string) {
|
||||
this.integrationName = integrationName;
|
||||
|
||||
const {
|
||||
username,
|
||||
password,
|
||||
url: credentialURL,
|
||||
} = JSON.parse(symmetricDecrypt(credential.key as string, CALENDSO_ENCRYPTION_KEY));
|
||||
|
||||
this.url = url || credentialURL;
|
||||
|
||||
this.credentials = { username, password };
|
||||
this.headers = getBasicAuthHeaders({ username, password });
|
||||
|
||||
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
||||
}
|
||||
|
||||
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
|
||||
try {
|
||||
const calendars = await this.listCalendars(event);
|
||||
|
||||
const uid = uuidv4();
|
||||
|
||||
// We create local ICS files
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: convertDate(event.startTime),
|
||||
duration: getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
/** according to https://datatracker.ietf.org/doc/html/rfc2446#section-3.2.1, in a published iCalendar component.
|
||||
* "Attendees" MUST NOT be present
|
||||
* `attendees: this.getAttendees(event.attendees),`
|
||||
*/
|
||||
});
|
||||
|
||||
if (error || !iCalString) throw new Error("Error creating iCalString");
|
||||
|
||||
// We create the event directly on iCal
|
||||
const responses = await Promise.all(
|
||||
calendars
|
||||
.filter((c) =>
|
||||
event.destinationCalendar?.externalId
|
||||
? c.externalId === event.destinationCalendar.externalId
|
||||
: true
|
||||
)
|
||||
.map((calendar) =>
|
||||
createCalendarObject({
|
||||
calendar: {
|
||||
url: calendar.externalId,
|
||||
},
|
||||
filename: `${uid}.ics`,
|
||||
// according to https://datatracker.ietf.org/doc/html/rfc4791#section-4.1, Calendar object resources contained in calendar collections MUST NOT specify the iCalendar METHOD property.
|
||||
iCalString: iCalString.replace(/METHOD:[^\r\n]+\r\n/g, ""),
|
||||
headers: this.headers,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
if (responses.some((r) => !r.ok)) {
|
||||
throw new Error(
|
||||
`Error creating event: ${(await Promise.all(responses.map((r) => r.text()))).join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
uid,
|
||||
id: uid,
|
||||
type: this.integrationName,
|
||||
password: "",
|
||||
url: "",
|
||||
additionalInfo: {},
|
||||
};
|
||||
} catch (reason) {
|
||||
logger.error(reason);
|
||||
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent) {
|
||||
try {
|
||||
const events = await this.getEventsByUID(uid);
|
||||
|
||||
/** We generate the ICS files */
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: convertDate(event.startTime),
|
||||
duration: getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
this.log.debug("Error creating iCalString");
|
||||
|
||||
return {
|
||||
type: event.type,
|
||||
id: typeof event.uid === "string" ? event.uid : "-1",
|
||||
password: "",
|
||||
url: typeof event.location === "string" ? event.location : "-1",
|
||||
};
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((e) => e.uid === uid);
|
||||
|
||||
return Promise.all(
|
||||
eventsToUpdate.map((e) => {
|
||||
return updateCalendarObject({
|
||||
calendarObject: {
|
||||
url: e.url,
|
||||
data: iCalString,
|
||||
etag: e?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
).then((p) => p.map((r) => r.json() as unknown as Event));
|
||||
} catch (reason) {
|
||||
this.log.error(reason);
|
||||
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string): Promise<void> {
|
||||
try {
|
||||
const events = await this.getEventsByUID(uid);
|
||||
|
||||
const eventsToDelete = events.filter((event) => event.uid === uid);
|
||||
|
||||
await Promise.all(
|
||||
eventsToDelete.map((event) => {
|
||||
return deleteCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
this.log.error(reason);
|
||||
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailability(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: IntegrationCalendar[]
|
||||
): Promise<EventBusyDate[]> {
|
||||
const objects = (
|
||||
await Promise.all(
|
||||
selectedCalendars
|
||||
.filter((sc) => ["caldav_calendar", "apple_calendar"].includes(sc.integration ?? ""))
|
||||
.map((sc) =>
|
||||
fetchCalendarObjects({
|
||||
calendar: {
|
||||
url: sc.externalId,
|
||||
},
|
||||
headers: this.headers,
|
||||
expand: true,
|
||||
timeRange: {
|
||||
start: new Date(dateFrom).toISOString(),
|
||||
end: new Date(dateTo).toISOString(),
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
).flat();
|
||||
|
||||
const events = objects
|
||||
.filter((e) => !!e.data)
|
||||
.map((object) => {
|
||||
const jcalData = ICAL.parse(object.data);
|
||||
const vcalendar = new ICAL.Component(jcalData);
|
||||
const vevent = vcalendar.getFirstSubcomponent("vevent");
|
||||
const event = new ICAL.Event(vevent);
|
||||
|
||||
return {
|
||||
start: event.startDate.toJSDate().toISOString(),
|
||||
end: event.endDate.toJSDate().toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
return Promise.resolve(events);
|
||||
}
|
||||
|
||||
async listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]> {
|
||||
try {
|
||||
const account = await this.getAccount();
|
||||
|
||||
const calendars = await fetchCalendars({
|
||||
account,
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return calendars.reduce<IntegrationCalendar[]>((newCalendars, calendar) => {
|
||||
if (!calendar.components?.includes("VEVENT")) return newCalendars;
|
||||
|
||||
newCalendars.push({
|
||||
externalId: calendar.url,
|
||||
name: calendar.displayName ?? "",
|
||||
primary: event?.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId === calendar.url
|
||||
: false,
|
||||
integration: this.integrationName,
|
||||
});
|
||||
return newCalendars;
|
||||
}, []);
|
||||
} catch (reason) {
|
||||
logger.error(reason);
|
||||
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
private async getEvents(
|
||||
calId: string,
|
||||
dateFrom: string | null,
|
||||
dateTo: string | null,
|
||||
objectUrls?: string[] | null
|
||||
) {
|
||||
try {
|
||||
const objects = await fetchCalendarObjects({
|
||||
calendar: {
|
||||
url: calId,
|
||||
},
|
||||
objectUrls: objectUrls ? objectUrls : undefined,
|
||||
timeRange:
|
||||
dateFrom && dateTo
|
||||
? {
|
||||
start: dayjs(dateFrom).utc().format(TIMEZONE_FORMAT),
|
||||
end: dayjs(dateTo).utc().format(TIMEZONE_FORMAT),
|
||||
}
|
||||
: undefined,
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
const events = objects
|
||||
.filter((e) => !!e.data)
|
||||
.map((object) => {
|
||||
const jcalData = ICAL.parse(object.data);
|
||||
|
||||
const vcalendar = new ICAL.Component(jcalData);
|
||||
|
||||
const vevent = vcalendar.getFirstSubcomponent("vevent");
|
||||
const event = new ICAL.Event(vevent);
|
||||
|
||||
const calendarTimezone =
|
||||
vcalendar.getFirstSubcomponent("vtimezone")?.getFirstPropertyValue("tzid") || "";
|
||||
|
||||
const startDate = calendarTimezone
|
||||
? dayjs.tz(event.startDate.toString(), calendarTimezone)
|
||||
: new Date(event.startDate.toUnixTime() * 1000);
|
||||
|
||||
const endDate = calendarTimezone
|
||||
? dayjs.tz(event.endDate.toString(), calendarTimezone)
|
||||
: new Date(event.endDate.toUnixTime() * 1000);
|
||||
|
||||
return {
|
||||
uid: event.uid,
|
||||
etag: object.etag,
|
||||
url: object.url,
|
||||
summary: event.summary,
|
||||
description: event.description,
|
||||
location: event.location,
|
||||
sequence: event.sequence,
|
||||
startDate,
|
||||
endDate,
|
||||
duration: {
|
||||
weeks: event.duration.weeks,
|
||||
days: event.duration.days,
|
||||
hours: event.duration.hours,
|
||||
minutes: event.duration.minutes,
|
||||
seconds: event.duration.seconds,
|
||||
isNegative: event.duration.isNegative,
|
||||
},
|
||||
organizer: event.organizer,
|
||||
attendees: event.attendees.map((a) => a.getValues()),
|
||||
recurrenceId: event.recurrenceId,
|
||||
timezone: calendarTimezone,
|
||||
};
|
||||
});
|
||||
|
||||
return events;
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
private async getEventsByUID(uid: string): Promise<CalendarEventType[]> {
|
||||
const events: Prisma.PromiseReturnType<typeof this.getEvents> = [];
|
||||
const calendars = await this.listCalendars();
|
||||
|
||||
for (const cal of calendars) {
|
||||
const calEvents = await this.getEvents(cal.externalId, null, null, [`${cal.externalId}${uid}.ics`]);
|
||||
|
||||
for (const ev of calEvents) {
|
||||
events.push(ev);
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
private async getAccount(): Promise<DAVAccount> {
|
||||
return createAccount({
|
||||
account: {
|
||||
serverUrl: this.url,
|
||||
accountType: CALDAV_CALENDAR_TYPE,
|
||||
credentials: this.credentials,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { CALENDAR_INTEGRATIONS_TYPES } from "../constants/generals";
|
||||
import CalendarService from "./BaseCalendarService";
|
||||
|
||||
export default class CalDavCalendarService extends CalendarService {
|
||||
constructor(credential: Credential) {
|
||||
super(credential, CALENDAR_INTEGRATIONS_TYPES.caldav);
|
||||
}
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
import { Credential, Prisma } from "@prisma/client";
|
||||
import { GetTokenResponse } from "google-auth-library/build/src/auth/oauth2client";
|
||||
import { Auth, calendar_v3, google } from "googleapis";
|
||||
|
||||
import { getLocation, getRichDescription } from "@lib/CalEventParser";
|
||||
import { CALENDAR_INTEGRATIONS_TYPES } from "@lib/integrations/calendar/constants/generals";
|
||||
import logger from "@lib/logger";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { EventBusyDate, NewCalendarEventType } from "../constants/types";
|
||||
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
|
||||
import CalendarService from "./BaseCalendarService";
|
||||
|
||||
const GOOGLE_API_CREDENTIALS = process.env.GOOGLE_API_CREDENTIALS || "";
|
||||
|
||||
export default class GoogleCalendarService implements Calendar {
|
||||
private url = "";
|
||||
private integrationName = "";
|
||||
private auth: { getToken: () => Promise<MyGoogleAuth> };
|
||||
private log: typeof logger;
|
||||
|
||||
constructor(credential: Credential) {
|
||||
this.integrationName = CALENDAR_INTEGRATIONS_TYPES.google;
|
||||
|
||||
this.auth = this.googleAuth(credential);
|
||||
|
||||
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
||||
}
|
||||
|
||||
private googleAuth = (credential: Credential) => {
|
||||
const { client_secret, client_id, redirect_uris } = JSON.parse(GOOGLE_API_CREDENTIALS).web;
|
||||
|
||||
const myGoogleAuth = new MyGoogleAuth(client_id, client_secret, redirect_uris[0]);
|
||||
|
||||
const googleCredentials = credential.key as Auth.Credentials;
|
||||
myGoogleAuth.setCredentials(googleCredentials);
|
||||
|
||||
const isExpired = () => myGoogleAuth.isTokenExpiring();
|
||||
|
||||
const refreshAccessToken = () =>
|
||||
myGoogleAuth
|
||||
.refreshToken(googleCredentials.refresh_token)
|
||||
.then((res: GetTokenResponse) => {
|
||||
const token = res.res?.data;
|
||||
googleCredentials.access_token = token.access_token;
|
||||
googleCredentials.expiry_date = token.expiry_date;
|
||||
return prisma.credential
|
||||
.update({
|
||||
where: {
|
||||
id: credential.id,
|
||||
},
|
||||
data: {
|
||||
key: googleCredentials as Prisma.InputJsonValue,
|
||||
},
|
||||
})
|
||||
.then(() => {
|
||||
myGoogleAuth.setCredentials(googleCredentials);
|
||||
return myGoogleAuth;
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
this.log.error("Error refreshing google token", err);
|
||||
|
||||
return myGoogleAuth;
|
||||
});
|
||||
|
||||
return {
|
||||
getToken: () => (!isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()),
|
||||
};
|
||||
};
|
||||
|
||||
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
|
||||
return new Promise((resolve, reject) =>
|
||||
this.auth.getToken().then((myGoogleAuth) => {
|
||||
const payload: calendar_v3.Schema$Event = {
|
||||
summary: event.title,
|
||||
description: getRichDescription(event),
|
||||
start: {
|
||||
dateTime: event.startTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
end: {
|
||||
dateTime: event.endTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
attendees: event.attendees.map((attendee) => ({
|
||||
...attendee,
|
||||
responseStatus: "accepted",
|
||||
})),
|
||||
reminders: {
|
||||
useDefault: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (event.location) {
|
||||
payload["location"] = getLocation(event);
|
||||
}
|
||||
|
||||
if (event.conferenceData && event.location === "integrations:google:meet") {
|
||||
payload["conferenceData"] = event.conferenceData;
|
||||
}
|
||||
|
||||
const calendar = google.calendar({
|
||||
version: "v3",
|
||||
auth: myGoogleAuth,
|
||||
});
|
||||
calendar.events.insert(
|
||||
{
|
||||
auth: myGoogleAuth,
|
||||
calendarId: event.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId
|
||||
: "primary",
|
||||
requestBody: payload,
|
||||
conferenceDataVersion: 1,
|
||||
},
|
||||
function (err, event) {
|
||||
if (err || !event?.data) {
|
||||
console.error("There was an error contacting google calendar service: ", err);
|
||||
return reject(err);
|
||||
}
|
||||
return resolve({
|
||||
uid: "",
|
||||
...event.data,
|
||||
id: event.data.id || "",
|
||||
additionalInfo: {
|
||||
hangoutLink: event.data.hangoutLink || "",
|
||||
},
|
||||
type: "google_calendar",
|
||||
password: "",
|
||||
url: "",
|
||||
});
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent): Promise<any> {
|
||||
return new Promise((resolve, reject) =>
|
||||
this.auth.getToken().then((myGoogleAuth) => {
|
||||
const payload: calendar_v3.Schema$Event = {
|
||||
summary: event.title,
|
||||
description: getRichDescription(event),
|
||||
start: {
|
||||
dateTime: event.startTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
end: {
|
||||
dateTime: event.endTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
attendees: event.attendees,
|
||||
reminders: {
|
||||
useDefault: true,
|
||||
},
|
||||
};
|
||||
|
||||
if (event.location) {
|
||||
payload["location"] = getLocation(event);
|
||||
}
|
||||
|
||||
const calendar = google.calendar({
|
||||
version: "v3",
|
||||
auth: myGoogleAuth,
|
||||
});
|
||||
calendar.events.update(
|
||||
{
|
||||
auth: myGoogleAuth,
|
||||
calendarId: event.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId
|
||||
: "primary",
|
||||
eventId: uid,
|
||||
sendNotifications: true,
|
||||
sendUpdates: "all",
|
||||
requestBody: payload,
|
||||
},
|
||||
function (err, event) {
|
||||
if (err) {
|
||||
console.error("There was an error contacting google calendar service: ", err);
|
||||
|
||||
return reject(err);
|
||||
}
|
||||
return resolve(event?.data);
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string, event: CalendarEvent): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
this.auth.getToken().then((myGoogleAuth) => {
|
||||
const calendar = google.calendar({
|
||||
version: "v3",
|
||||
auth: myGoogleAuth,
|
||||
});
|
||||
calendar.events.delete(
|
||||
{
|
||||
auth: myGoogleAuth,
|
||||
calendarId: event.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId
|
||||
: "primary",
|
||||
eventId: uid,
|
||||
sendNotifications: true,
|
||||
sendUpdates: "all",
|
||||
},
|
||||
function (err, event) {
|
||||
if (err) {
|
||||
console.error("There was an error contacting google calendar service: ", err);
|
||||
return reject(err);
|
||||
}
|
||||
return resolve(event?.data);
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async getAvailability(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: IntegrationCalendar[]
|
||||
): Promise<EventBusyDate[]> {
|
||||
return new Promise((resolve, reject) =>
|
||||
this.auth.getToken().then((myGoogleAuth) => {
|
||||
const calendar = google.calendar({
|
||||
version: "v3",
|
||||
auth: myGoogleAuth,
|
||||
});
|
||||
const selectedCalendarIds = selectedCalendars
|
||||
.filter((e) => e.integration === this.integrationName)
|
||||
.map((e) => e.externalId);
|
||||
if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
|
||||
// Only calendars of other integrations selected
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
|
||||
(selectedCalendarIds.length === 0
|
||||
? calendar.calendarList
|
||||
.list()
|
||||
.then((cals) => cals.data.items?.map((cal) => cal.id).filter(Boolean) || [])
|
||||
: Promise.resolve(selectedCalendarIds)
|
||||
)
|
||||
.then((calsIds) => {
|
||||
calendar.freebusy.query(
|
||||
{
|
||||
requestBody: {
|
||||
timeMin: dateFrom,
|
||||
timeMax: dateTo,
|
||||
items: calsIds.map((id) => ({ id: id })),
|
||||
},
|
||||
},
|
||||
(err, apires) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
let result: Prisma.PromiseReturnType<CalendarService["getAvailability"]> = [];
|
||||
|
||||
if (apires?.data.calendars) {
|
||||
result = Object.values(apires.data.calendars).reduce((c, i) => {
|
||||
i.busy?.forEach((busyTime) => {
|
||||
c.push({
|
||||
start: busyTime.start || "",
|
||||
end: busyTime.end || "",
|
||||
});
|
||||
});
|
||||
return c;
|
||||
}, [] as typeof result);
|
||||
}
|
||||
resolve(result);
|
||||
}
|
||||
);
|
||||
})
|
||||
.catch((err) => {
|
||||
this.log.error("There was an error contacting google calendar service: ", err);
|
||||
|
||||
reject(err);
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async listCalendars(): Promise<IntegrationCalendar[]> {
|
||||
return new Promise((resolve, reject) =>
|
||||
this.auth.getToken().then((myGoogleAuth) => {
|
||||
const calendar = google.calendar({
|
||||
version: "v3",
|
||||
auth: myGoogleAuth,
|
||||
});
|
||||
|
||||
calendar.calendarList
|
||||
.list()
|
||||
.then((cals) => {
|
||||
resolve(
|
||||
cals.data.items?.map((cal) => {
|
||||
const calendar: IntegrationCalendar = {
|
||||
externalId: cal.id ?? "No id",
|
||||
integration: this.integrationName,
|
||||
name: cal.summary ?? "No name",
|
||||
primary: cal.primary ?? false,
|
||||
};
|
||||
return calendar;
|
||||
}) || []
|
||||
);
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
this.log.error("There was an error contacting google calendar service: ", err);
|
||||
|
||||
reject(err);
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyGoogleAuth extends google.auth.OAuth2 {
|
||||
constructor(client_id: string, client_secret: string, redirect_uri: string) {
|
||||
super(client_id, client_secret, redirect_uri);
|
||||
}
|
||||
|
||||
isTokenExpiring() {
|
||||
return super.isTokenExpiring();
|
||||
}
|
||||
|
||||
async refreshToken(token: string | null | undefined) {
|
||||
return super.refreshToken(token);
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import { Calendar as OfficeCalendar } from "@microsoft/microsoft-graph-types-beta";
|
||||
import { Credential } from "@prisma/client";
|
||||
|
||||
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
|
||||
|
||||
import { getLocation, getRichDescription } from "@lib/CalEventParser";
|
||||
import { CALENDAR_INTEGRATIONS_TYPES } from "@lib/integrations/calendar/constants/generals";
|
||||
import logger from "@lib/logger";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { BatchResponse, EventBusyDate, NewCalendarEventType } from "../constants/types";
|
||||
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
|
||||
import { BufferedBusyTime, O365AuthCredentials } from "../interfaces/Office365Calendar";
|
||||
|
||||
const MS_GRAPH_CLIENT_ID = process.env.MS_GRAPH_CLIENT_ID || "";
|
||||
const MS_GRAPH_CLIENT_SECRET = process.env.MS_GRAPH_CLIENT_SECRET || "";
|
||||
|
||||
export default class Office365CalendarService implements Calendar {
|
||||
private url = "";
|
||||
private integrationName = "";
|
||||
private log: typeof logger;
|
||||
auth: { getToken: () => Promise<string> };
|
||||
|
||||
constructor(credential: Credential) {
|
||||
this.integrationName = CALENDAR_INTEGRATIONS_TYPES.office365;
|
||||
this.auth = this.o365Auth(credential);
|
||||
|
||||
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
||||
}
|
||||
|
||||
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
|
||||
try {
|
||||
const accessToken = await this.auth.getToken();
|
||||
|
||||
const calendarId = event.destinationCalendar?.externalId
|
||||
? `${event.destinationCalendar.externalId}/`
|
||||
: "";
|
||||
|
||||
const response = await fetch(`https://graph.microsoft.com/v1.0/me/calendar/events`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(this.translateEvent(event)),
|
||||
});
|
||||
|
||||
return handleErrorsJson(response);
|
||||
} catch (error) {
|
||||
this.log.error(error);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent): Promise<any> {
|
||||
try {
|
||||
const accessToken = await this.auth.getToken();
|
||||
|
||||
const response = await fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(this.translateEvent(event)),
|
||||
});
|
||||
|
||||
return handleErrorsRaw(response);
|
||||
} catch (error) {
|
||||
this.log.error(error);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string): Promise<void> {
|
||||
try {
|
||||
const accessToken = await this.auth.getToken();
|
||||
|
||||
const response = await fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
},
|
||||
});
|
||||
|
||||
handleErrorsRaw(response);
|
||||
} catch (error) {
|
||||
this.log.error(error);
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailability(
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: IntegrationCalendar[]
|
||||
): Promise<EventBusyDate[]> {
|
||||
const dateFromParsed = new Date(dateFrom);
|
||||
const dateToParsed = new Date(dateTo);
|
||||
|
||||
const filter = `?startdatetime=${encodeURIComponent(
|
||||
dateFromParsed.toISOString()
|
||||
)}&enddatetime=${encodeURIComponent(dateToParsed.toISOString())}`;
|
||||
return this.auth
|
||||
.getToken()
|
||||
.then((accessToken) => {
|
||||
const selectedCalendarIds = selectedCalendars
|
||||
.filter((e) => e.integration === this.integrationName)
|
||||
.map((e) => e.externalId)
|
||||
.filter(Boolean);
|
||||
if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
|
||||
// Only calendars of other integrations selected
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
selectedCalendarIds.length === 0
|
||||
? this.listCalendars().then((cals) => cals.map((e) => e.externalId).filter(Boolean) || [])
|
||||
: Promise.resolve(selectedCalendarIds)
|
||||
).then((ids) => {
|
||||
const requests = ids.map((calendarId, id) => ({
|
||||
id,
|
||||
method: "GET",
|
||||
url: `/me/calendars/${calendarId}/calendarView${filter}`,
|
||||
}));
|
||||
|
||||
return fetch("https://graph.microsoft.com/v1.0/$batch", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ requests }),
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then((responseBody: BatchResponse) =>
|
||||
responseBody.responses.reduce(
|
||||
(acc: BufferedBusyTime[], subResponse) =>
|
||||
acc.concat(
|
||||
subResponse.body.value.map((evt) => {
|
||||
return {
|
||||
start: evt.start.dateTime + "Z",
|
||||
end: evt.end.dateTime + "Z",
|
||||
};
|
||||
})
|
||||
),
|
||||
[]
|
||||
)
|
||||
);
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
return Promise.reject([]);
|
||||
});
|
||||
}
|
||||
|
||||
async listCalendars(): Promise<IntegrationCalendar[]> {
|
||||
return this.auth.getToken().then((accessToken) =>
|
||||
fetch("https://graph.microsoft.com/v1.0/me/calendars", {
|
||||
method: "get",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then((responseBody: { value: OfficeCalendar[] }) => {
|
||||
return responseBody.value.map((cal) => {
|
||||
const calendar: IntegrationCalendar = {
|
||||
externalId: cal.id ?? "No Id",
|
||||
integration: this.integrationName,
|
||||
name: cal.name ?? "No calendar name",
|
||||
primary: cal.isDefaultCalendar ?? false,
|
||||
};
|
||||
return calendar;
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private o365Auth = (credential: Credential) => {
|
||||
const isExpired = (expiryDate: number) => expiryDate < Math.round(+new Date() / 1000);
|
||||
|
||||
const o365AuthCredentials = credential.key as O365AuthCredentials;
|
||||
|
||||
const refreshAccessToken = (refreshToken: string) => {
|
||||
return fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
scope: "User.Read Calendars.Read Calendars.ReadWrite",
|
||||
client_id: MS_GRAPH_CLIENT_ID,
|
||||
refresh_token: refreshToken,
|
||||
grant_type: "refresh_token",
|
||||
client_secret: MS_GRAPH_CLIENT_SECRET,
|
||||
}),
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then((responseBody) => {
|
||||
o365AuthCredentials.access_token = responseBody.access_token;
|
||||
o365AuthCredentials.expiry_date = Math.round(+new Date() / 1000 + responseBody.expires_in);
|
||||
return prisma.credential
|
||||
.update({
|
||||
where: {
|
||||
id: credential.id,
|
||||
},
|
||||
data: {
|
||||
key: o365AuthCredentials,
|
||||
},
|
||||
})
|
||||
.then(() => o365AuthCredentials.access_token);
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
getToken: () =>
|
||||
!isExpired(o365AuthCredentials.expiry_date)
|
||||
? Promise.resolve(o365AuthCredentials.access_token)
|
||||
: refreshAccessToken(o365AuthCredentials.refresh_token),
|
||||
};
|
||||
};
|
||||
|
||||
private translateEvent = (event: CalendarEvent) => {
|
||||
return {
|
||||
subject: event.title,
|
||||
body: {
|
||||
contentType: "HTML",
|
||||
content: getRichDescription(event),
|
||||
},
|
||||
start: {
|
||||
dateTime: event.startTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
end: {
|
||||
dateTime: event.endTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
attendees: event.attendees.map((attendee) => ({
|
||||
emailAddress: {
|
||||
address: attendee.email,
|
||||
name: attendee.name,
|
||||
},
|
||||
type: "required",
|
||||
})),
|
||||
location: event.location ? { displayName: getLocation(event) } : undefined,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import { Attendee, DateArray, DurationObject, Person } from "ics";
|
||||
|
||||
export const convertDate = (date: string): DateArray =>
|
||||
dayjs(date)
|
||||
.utc()
|
||||
.toArray()
|
||||
.slice(0, 6)
|
||||
.map((v, i) => (i === 1 ? v + 1 : v)) as DateArray;
|
||||
|
||||
export const getDuration = (start: string, end: string): DurationObject => ({
|
||||
minutes: dayjs(end).diff(dayjs(start), "minute"),
|
||||
});
|
||||
|
||||
export const getAttendees = (attendees: Person[]): Attendee[] =>
|
||||
attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
|
||||
@@ -1,164 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import _ from "lodash";
|
||||
|
||||
import { validJson } from "@lib/jsonUtils";
|
||||
|
||||
const credentialData = Prisma.validator<Prisma.CredentialArgs>()({
|
||||
select: { id: true, type: true },
|
||||
});
|
||||
|
||||
type CredentialData = Prisma.CredentialGetPayload<typeof credentialData>;
|
||||
|
||||
export type Integration = {
|
||||
installed: boolean;
|
||||
type:
|
||||
| "google_calendar"
|
||||
| "office365_calendar"
|
||||
| "zoom_video"
|
||||
| "daily_video"
|
||||
| "tandem_video"
|
||||
| "caldav_calendar"
|
||||
| "apple_calendar"
|
||||
| "stripe_payment"
|
||||
| "jitsi_video"
|
||||
| "huddle01_video"
|
||||
| "metamask_web3";
|
||||
title: string;
|
||||
imageSrc: string;
|
||||
description: string;
|
||||
variant: "calendar" | "conferencing" | "payment" | "web3";
|
||||
};
|
||||
|
||||
export const ALL_INTEGRATIONS = [
|
||||
{
|
||||
installed: !!(process.env.GOOGLE_API_CREDENTIALS && validJson(process.env.GOOGLE_API_CREDENTIALS)),
|
||||
type: "google_calendar",
|
||||
title: "Google Calendar",
|
||||
imageSrc: "integrations/google-calendar.svg",
|
||||
description: "For personal and business calendars",
|
||||
variant: "calendar",
|
||||
},
|
||||
{
|
||||
installed: !!(process.env.MS_GRAPH_CLIENT_ID && process.env.MS_GRAPH_CLIENT_SECRET),
|
||||
type: "office365_calendar",
|
||||
title: "Office 365 / Outlook.com Calendar",
|
||||
imageSrc: "integrations/outlook.svg",
|
||||
description: "For personal and business calendars",
|
||||
variant: "calendar",
|
||||
},
|
||||
{
|
||||
installed: !!(process.env.ZOOM_CLIENT_ID && process.env.ZOOM_CLIENT_SECRET),
|
||||
type: "zoom_video",
|
||||
title: "Zoom",
|
||||
imageSrc: "integrations/zoom.svg",
|
||||
description: "Video Conferencing",
|
||||
variant: "conferencing",
|
||||
},
|
||||
{
|
||||
installed: !!process.env.DAILY_API_KEY,
|
||||
type: "daily_video",
|
||||
title: "Daily.co Video",
|
||||
imageSrc: "integrations/daily.svg",
|
||||
description: "Video Conferencing",
|
||||
variant: "conferencing",
|
||||
},
|
||||
{
|
||||
installed: true,
|
||||
type: "jitsi_video",
|
||||
title: "Jitsi Meet",
|
||||
imageSrc: "integrations/jitsi.svg",
|
||||
description: "Video Conferencing",
|
||||
variant: "conferencing",
|
||||
},
|
||||
{
|
||||
installed: true,
|
||||
type: "huddle01_video",
|
||||
title: "Huddle01",
|
||||
imageSrc: "integrations/huddle.svg",
|
||||
description: "Video Conferencing",
|
||||
variant: "conferencing",
|
||||
},
|
||||
{
|
||||
installed: !!(process.env.TANDEM_CLIENT_ID && process.env.TANDEM_CLIENT_SECRET),
|
||||
type: "tandem_video",
|
||||
title: "Tandem Video",
|
||||
imageSrc: "integrations/tandem.svg",
|
||||
description: "Virtual Office | Video Conferencing",
|
||||
variant: "conferencing",
|
||||
},
|
||||
{
|
||||
installed: true,
|
||||
type: "caldav_calendar",
|
||||
title: "CalDav Server",
|
||||
imageSrc: "integrations/caldav.svg",
|
||||
description: "For personal and business calendars",
|
||||
variant: "calendar",
|
||||
},
|
||||
{
|
||||
installed: true,
|
||||
type: "apple_calendar",
|
||||
title: "Apple Calendar",
|
||||
imageSrc: "integrations/apple-calendar.svg",
|
||||
description: "For personal and business calendars",
|
||||
variant: "calendar",
|
||||
},
|
||||
{
|
||||
installed: !!(
|
||||
process.env.STRIPE_CLIENT_ID &&
|
||||
process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY &&
|
||||
process.env.STRIPE_PRIVATE_KEY
|
||||
),
|
||||
type: "stripe_payment",
|
||||
title: "Stripe",
|
||||
imageSrc: "integrations/stripe.svg",
|
||||
description: "Collect payments",
|
||||
variant: "payment",
|
||||
},
|
||||
{
|
||||
installed: true,
|
||||
type: "metamask_web3",
|
||||
title: "Metamask",
|
||||
imageSrc: "integrations/apple-calendar.svg",
|
||||
description: "For personal and business calendars",
|
||||
variant: "web3",
|
||||
},
|
||||
] as Integration[];
|
||||
|
||||
function getIntegrations(userCredentials: CredentialData[]) {
|
||||
const integrations = ALL_INTEGRATIONS.map((integration) => {
|
||||
const credentials = userCredentials
|
||||
.filter((credential) => credential.type === integration.type)
|
||||
.map((credential) => _.pick(credential, ["id", "type"])); // ensure we don't leak `key` to frontend
|
||||
|
||||
const credential: typeof credentials[number] | null = credentials[0] || null;
|
||||
return {
|
||||
...integration,
|
||||
/**
|
||||
* @deprecated use `credentials`
|
||||
*/
|
||||
credential,
|
||||
credentials,
|
||||
};
|
||||
});
|
||||
|
||||
return integrations;
|
||||
}
|
||||
|
||||
export type IntegrationMeta = ReturnType<typeof getIntegrations>;
|
||||
|
||||
export function hasIntegration(integrations: IntegrationMeta, type: string): boolean {
|
||||
return !!integrations.find(
|
||||
(i) =>
|
||||
i.type === type &&
|
||||
!!i.installed &&
|
||||
(type === "daily_video" ||
|
||||
type === "jitsi_video" ||
|
||||
type === "huddle01_video" ||
|
||||
i.credentials.length > 0)
|
||||
);
|
||||
}
|
||||
export function hasIntegrationInstalled(type: Integration["type"]): boolean {
|
||||
return ALL_INTEGRATIONS.some((i) => i.type === type && !!i.installed);
|
||||
}
|
||||
|
||||
export default getIntegrations;
|
||||
@@ -1,11 +0,0 @@
|
||||
export const validJson = (jsonString: string) => {
|
||||
try {
|
||||
const o = JSON.parse(jsonString);
|
||||
if (o && typeof o === "object") {
|
||||
return o;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Invalid JSON:", e);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -1,20 +0,0 @@
|
||||
import { Logger } from "tslog";
|
||||
|
||||
import { IS_PRODUCTION } from "@lib/config/constants";
|
||||
|
||||
const logger = new Logger({
|
||||
dateTimePattern: "hour:minute:second.millisecond timeZoneName",
|
||||
displayFunctionName: false,
|
||||
displayFilePath: "hidden",
|
||||
dateTimeTimezone: IS_PRODUCTION ? "utc" : Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
prettyInspectHighlightStyles: {
|
||||
name: "yellow",
|
||||
number: "blue",
|
||||
bigint: "blue",
|
||||
boolean: "blue",
|
||||
},
|
||||
maskValuesOfKeys: ["password", "passwordConfirmation", "credentials", "credential"],
|
||||
exposeErrorCodeFrame: !IS_PRODUCTION,
|
||||
});
|
||||
|
||||
export default logger;
|
||||
@@ -1,3 +0,0 @@
|
||||
const notEmpty = <T>(value: T): value is NonNullable<typeof value> => !!value;
|
||||
|
||||
export default notEmpty;
|
||||
@@ -1,10 +1,10 @@
|
||||
// import { getBusyVideoTimes } from "@lib/videoClient";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
|
||||
|
||||
import { asStringOrNull } from "@lib/asStringOrNull";
|
||||
import { getWorkingHours } from "@lib/availability";
|
||||
import { getBusyCalendarTimes } from "@lib/integrations/calendar/CalendarManager";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export async function getUserAvailability(query: {
|
||||
@@ -67,8 +67,6 @@ export async function getUserAvailability(query: {
|
||||
selectedCalendars
|
||||
);
|
||||
|
||||
// busyTimes.push(...await getBusyVideoTimes(currentUser.credentials, dateFrom.format(), dateTo.format()));
|
||||
|
||||
const bufferedBusyTimes = busyTimes.map((a) => ({
|
||||
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
|
||||
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
|
||||
|
||||
@@ -1,9 +1,2 @@
|
||||
export const randomString = function (length = 12) {
|
||||
let result = "";
|
||||
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
const charactersLength = characters.length;
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// TODO: Remove this file once everything is imported from `@calcom/lib`
|
||||
export * from "@calcom/lib/random";
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
export const isBrowserLocale24h = () => {
|
||||
let locale = "en-US";
|
||||
if (process.browser && navigator) locale = navigator?.language;
|
||||
if (typeof window !== "undefined" && navigator) locale = navigator?.language;
|
||||
return !new Intl.DateTimeFormat(locale, { hour: "numeric" }).format(0).match(/AM/);
|
||||
};
|
||||
export const detectBrowserTimeFormat = isBrowserLocale24h() ? "H:mm" : "h:mma";
|
||||
@@ -1,7 +0,0 @@
|
||||
/** Makes selected props from a record non optional */
|
||||
export type Ensure<T, K extends keyof T> = Omit<T, K> & {
|
||||
[EK in K]-?: NonNullable<T[EK]>;
|
||||
};
|
||||
|
||||
/** Makes selected props from a record optional */
|
||||
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
|
||||
@@ -1,148 +0,0 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import short from "short-uuid";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import { getUid } from "@lib/CalEventParser";
|
||||
import { EventResult } from "@lib/events/EventManager";
|
||||
import { PartialReference } from "@lib/events/EventManager";
|
||||
import Huddle01VideoApiAdapter from "@lib/integrations/Huddle01/Huddle01VideoApiAdapter";
|
||||
import JitsiVideoApiAdapter from "@lib/integrations/Jitsi/JitsiVideoApiAdapter";
|
||||
import logger from "@lib/logger";
|
||||
|
||||
import DailyVideoApiAdapter from "./integrations/Daily/DailyVideoApiAdapter";
|
||||
import TandemVideoApiAdapter from "./integrations/Tandem/TandemVideoApiAdapter";
|
||||
import ZoomVideoApiAdapter from "./integrations/Zoom/ZoomVideoApiAdapter";
|
||||
import { CalendarEvent } from "./integrations/calendar/interfaces/Calendar";
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[lib] videoClient"] });
|
||||
|
||||
const translator = short();
|
||||
|
||||
export interface VideoCallData {
|
||||
type: string;
|
||||
id: string;
|
||||
password: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type EventBusyDate = Record<"start" | "end", Date>;
|
||||
|
||||
export interface VideoApiAdapter {
|
||||
createMeeting(event: CalendarEvent): Promise<VideoCallData>;
|
||||
|
||||
updateMeeting(bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData>;
|
||||
|
||||
deleteMeeting(uid: string): Promise<unknown>;
|
||||
|
||||
getAvailability(dateFrom?: string, dateTo?: string): Promise<EventBusyDate[]>;
|
||||
}
|
||||
|
||||
// factory
|
||||
const getVideoAdapters = (withCredentials: Credential[]): VideoApiAdapter[] =>
|
||||
withCredentials.reduce<VideoApiAdapter[]>((acc, cred) => {
|
||||
switch (cred.type) {
|
||||
case "zoom_video":
|
||||
acc.push(ZoomVideoApiAdapter(cred));
|
||||
break;
|
||||
case "daily_video":
|
||||
acc.push(DailyVideoApiAdapter(cred));
|
||||
break;
|
||||
case "jitsi_video":
|
||||
acc.push(JitsiVideoApiAdapter());
|
||||
break;
|
||||
case "huddle01_video":
|
||||
acc.push(Huddle01VideoApiAdapter());
|
||||
break;
|
||||
case "tandem_video":
|
||||
acc.push(TandemVideoApiAdapter(cred));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const getBusyVideoTimes = (withCredentials: Credential[]) =>
|
||||
Promise.all(getVideoAdapters(withCredentials).map((c) => c.getAvailability())).then((results) =>
|
||||
results.reduce((acc, availability) => acc.concat(availability), [])
|
||||
);
|
||||
|
||||
const createMeeting = async (credential: Credential, calEvent: CalendarEvent): Promise<EventResult> => {
|
||||
const uid: string = getUid(calEvent);
|
||||
|
||||
if (!credential) {
|
||||
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 = getVideoAdapters([credential]);
|
||||
const [firstVideoAdapter] = videoAdapters;
|
||||
const createdMeeting = await firstVideoAdapter.createMeeting(calEvent).catch((e) => {
|
||||
log.error("createMeeting failed", e, calEvent);
|
||||
});
|
||||
|
||||
if (!createdMeeting) {
|
||||
return {
|
||||
type: credential.type,
|
||||
success: false,
|
||||
uid,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success: true,
|
||||
uid,
|
||||
createdEvent: createdMeeting,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
};
|
||||
|
||||
const updateMeeting = async (
|
||||
credential: Credential,
|
||||
calEvent: CalendarEvent,
|
||||
bookingRef: PartialReference | null
|
||||
): Promise<EventResult> => {
|
||||
const uid = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
||||
|
||||
let success = true;
|
||||
|
||||
const [firstVideoAdapter] = getVideoAdapters([credential]);
|
||||
const updatedMeeting =
|
||||
credential && bookingRef
|
||||
? await firstVideoAdapter.updateMeeting(bookingRef, calEvent).catch((e) => {
|
||||
log.error("updateMeeting failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (!updatedMeeting) {
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
updatedEvent: updatedMeeting,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
};
|
||||
|
||||
const deleteMeeting = (credential: Credential, uid: string): Promise<unknown> => {
|
||||
if (credential) {
|
||||
return getVideoAdapters([credential])[0].deleteMeeting(uid);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
export { getBusyVideoTimes, createMeeting, updateMeeting, deleteMeeting };
|
||||
@@ -1,6 +1,6 @@
|
||||
import { compile } from "handlebars";
|
||||
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
type ContentType = "application/json" | "application/x-www-form-urlencoded";
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
const withTM = require("next-transpile-modules")([
|
||||
"@calcom/app-store",
|
||||
"@calcom/core",
|
||||
"@calcom/ee",
|
||||
"@calcom/lib",
|
||||
"@calcom/prisma",
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxyhq/saml-jackson": "0.3.6",
|
||||
"@calcom/app-store": "*",
|
||||
"@calcom/core": "*",
|
||||
"@calcom/ee": "*",
|
||||
"@calcom/lib": "*",
|
||||
"@calcom/prisma": "*",
|
||||
@@ -34,6 +36,7 @@
|
||||
"@calcom/tsconfig": "*",
|
||||
"@calcom/ui": "*",
|
||||
"@daily-co/daily-js": "^0.21.0",
|
||||
"@glidejs/glide": "^3.5.2",
|
||||
"@heroicons/react": "^1.0.5",
|
||||
"@hookform/error-message": "^2.0.0",
|
||||
"@hookform/resolvers": "^2.8.5",
|
||||
@@ -100,19 +103,19 @@
|
||||
"short-uuid": "^4.2.0",
|
||||
"stripe": "^8.191.0",
|
||||
"superjson": "1.8.1",
|
||||
"tsdav": "2.0.0",
|
||||
"tslog": "^3.2.1",
|
||||
"uuid": "^8.3.2",
|
||||
"web3": "^1.6.1",
|
||||
"zod": "^3.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@calcom/config": "*",
|
||||
"@calcom/types": "*",
|
||||
"@microsoft/microsoft-graph-types-beta": "0.15.0-preview",
|
||||
"@playwright/test": "^1.18.1",
|
||||
"@types/accept-language-parser": "1.5.2",
|
||||
"@types/async": "^3.2.10",
|
||||
"@types/bcryptjs": "^2.4.2",
|
||||
"@types/glidejs__glide": "^3.4.1",
|
||||
"@types/jest": "^27.0.3",
|
||||
"@types/lodash": "^4.14.177",
|
||||
"@types/micro": "^7.3.6",
|
||||
|
||||
@@ -7,9 +7,9 @@ import NextError, { ErrorProps } from "next/error";
|
||||
import React from "react";
|
||||
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
import { HttpError } from "@lib/core/http/error";
|
||||
import logger from "@lib/logger";
|
||||
|
||||
import { ErrorPage } from "@components/error/error-page";
|
||||
|
||||
|
||||
@@ -5,8 +5,9 @@ import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import GoogleProvider from "next-auth/providers/google";
|
||||
import { authenticator } from "otplib";
|
||||
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
|
||||
import { ErrorCode, verifyPassword } from "@lib/auth";
|
||||
import { symmetricDecrypt } from "@lib/crypto";
|
||||
import prisma from "@lib/prisma";
|
||||
import { randomString } from "@lib/random";
|
||||
import { isSAMLLoginEnabled, samlLoginUrl, hostedCal } from "@lib/saml";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { authenticator } from "otplib";
|
||||
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
|
||||
import { ErrorCode, getSession } from "@lib/auth";
|
||||
import { symmetricDecrypt } from "@lib/crypto";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
@@ -3,8 +3,9 @@ import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { authenticator } from "otplib";
|
||||
import qrcode from "qrcode";
|
||||
|
||||
import { symmetricEncrypt } from "@calcom/lib/crypto";
|
||||
|
||||
import { ErrorCode, getSession, verifyPassword } from "@lib/auth";
|
||||
import { symmetricEncrypt } from "@lib/crypto";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// import { getBusyVideoTimes } from "@lib/videoClient";
|
||||
// import { getBusyVideoTimes } from "@calcom/core/videoClient";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
|
||||
|
||||
import { asStringOrNull } from "@lib/asStringOrNull";
|
||||
import { getWorkingHours } from "@lib/availability";
|
||||
import { getBusyCalendarTimes } from "@lib/integrations/calendar/CalendarManager";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import notEmpty from "@calcom/lib/notEmpty";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@lib/integrations/calendar/CalendarManager";
|
||||
import notEmpty from "@lib/notEmpty";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { Prisma, User, Booking, SchedulingType, BookingStatus } from "@prisma/client";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { AdditionInformation } from "@calcom/types/Calendar";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import { refund } from "@ee/lib/stripe/server";
|
||||
|
||||
import { asStringOrNull } from "@lib/asStringOrNull";
|
||||
import { getSession } from "@lib/auth";
|
||||
import { sendDeclinedEmails } from "@lib/emails/email-manager";
|
||||
import { sendScheduledEmails } from "@lib/emails/email-manager";
|
||||
import EventManager from "@lib/events/EventManager";
|
||||
import { CalendarEvent, AdditionInformation } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import logger from "@lib/logger";
|
||||
import prisma from "@lib/prisma";
|
||||
import { BookingConfirmBody } from "@lib/types/booking";
|
||||
|
||||
|
||||
@@ -9,27 +9,27 @@ import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import short from "short-uuid";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import { getBusyVideoTimes } from "@calcom/core/videoClient";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import notEmpty from "@calcom/lib/notEmpty";
|
||||
import type { BufferedBusyTime } from "@calcom/types/BufferedBusyTime";
|
||||
import type { AdditionInformation, CalendarEvent, EventBusyDate } from "@calcom/types/Calendar";
|
||||
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
|
||||
import { handlePayment } from "@ee/lib/stripe/server";
|
||||
|
||||
import {
|
||||
sendScheduledEmails,
|
||||
sendRescheduledEmails,
|
||||
sendOrganizerRequestEmail,
|
||||
sendAttendeeRequestEmail,
|
||||
sendOrganizerRequestEmail,
|
||||
sendRescheduledEmails,
|
||||
sendScheduledEmails,
|
||||
} from "@lib/emails/email-manager";
|
||||
import { ensureArray } from "@lib/ensureArray";
|
||||
import { getEventName } from "@lib/event";
|
||||
import EventManager, { EventResult, PartialReference } from "@lib/events/EventManager";
|
||||
import { getBusyCalendarTimes } from "@lib/integrations/calendar/CalendarManager";
|
||||
import { EventBusyDate } from "@lib/integrations/calendar/constants/types";
|
||||
import { CalendarEvent, AdditionInformation } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import { BufferedBusyTime } from "@lib/integrations/calendar/interfaces/Office365Calendar";
|
||||
import logger from "@lib/logger";
|
||||
import notEmpty from "@lib/notEmpty";
|
||||
import prisma from "@lib/prisma";
|
||||
import { BookingCreateBody } from "@lib/types/booking";
|
||||
import { getBusyVideoTimes } from "@lib/videoClient";
|
||||
import sendPayload from "@lib/webhooks/sendPayload";
|
||||
import getSubscribers from "@lib/webhooks/subscriptions";
|
||||
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { BookingStatus, WebhookTriggerEvents } from "@prisma/client";
|
||||
import { BookingStatus, Credential, WebhookTriggerEvents } from "@prisma/client";
|
||||
import async from "async";
|
||||
import dayjs from "dayjs";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
|
||||
import { getCalendar } from "@calcom/core/CalendarManager";
|
||||
import { deleteMeeting } from "@calcom/core/videoClient";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import { refund } from "@ee/lib/stripe/server";
|
||||
|
||||
import { asStringOrNull } from "@lib/asStringOrNull";
|
||||
import { getSession } from "@lib/auth";
|
||||
import { sendCancelledEmails } from "@lib/emails/email-manager";
|
||||
import { FAKE_DAILY_CREDENTIAL } from "@lib/integrations/Daily/DailyVideoApiAdapter";
|
||||
import { getCalendar } from "@lib/integrations/calendar/CalendarManager";
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import prisma from "@lib/prisma";
|
||||
import { deleteMeeting } from "@lib/videoClient";
|
||||
import sendPayload from "@lib/webhooks/sendPayload";
|
||||
import getSubscribers from "@lib/webhooks/subscriptions";
|
||||
|
||||
@@ -159,11 +159,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
},
|
||||
});
|
||||
|
||||
/** TODO: Remove this without breaking functionality */
|
||||
if (bookingToDelete.location === "integrations:daily") {
|
||||
bookingToDelete.user.credentials.push(FAKE_DAILY_CREDENTIAL);
|
||||
}
|
||||
|
||||
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential) => {
|
||||
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential: Credential) => {
|
||||
const bookingRefUid = bookingToDelete.references.filter((ref) => ref.type === credential.type)[0]?.uid;
|
||||
if (bookingRefUid) {
|
||||
if (credential.type.endsWith("_calendar")) {
|
||||
|
||||
@@ -2,8 +2,9 @@ import { ReminderType } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { sendOrganizerRequestReminderEmail } from "@lib/emails/email-manager";
|
||||
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { getTranslation } from "@server/lib/i18n";
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import appStore from "@calcom/app-store";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { HttpError } from "@lib/core/http/error";
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
// Check that user is authenticated
|
||||
req.session = await getSession({ req });
|
||||
|
||||
if (!req.session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { args } = req.query;
|
||||
|
||||
if (!Array.isArray(args)) {
|
||||
return res.status(404).json({ message: `API route not found` });
|
||||
}
|
||||
|
||||
const [_appName, apiEndpoint] = args;
|
||||
const appName = _appName.split("_").join(""); // Transform `zoom_video` to `zoomvideo`;
|
||||
|
||||
try {
|
||||
// TODO: Find a way to dynamically import these modules
|
||||
// const app = (await import(`@calcom/${appName}`)).default;
|
||||
const handler = appStore[appName].api[apiEndpoint];
|
||||
if (typeof handler !== "function")
|
||||
throw new HttpError({ statusCode: 404, message: `API handler not found` });
|
||||
|
||||
const response = await handler(req, res);
|
||||
console.log("response", response);
|
||||
|
||||
res.status(200);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (error instanceof HttpError) {
|
||||
return res.status(error.statusCode).json({ message: error.message });
|
||||
}
|
||||
return res.status(404).json({ message: `API handler not found` });
|
||||
}
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { symmetricEncrypt } from "@lib/crypto";
|
||||
import { getCalendar } from "@lib/integrations/calendar/CalendarManager";
|
||||
import logger from "@lib/logger";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { username, password } = req.body;
|
||||
// Get user
|
||||
const user = await prisma.user.findFirst({
|
||||
rejectOnNotFound: true,
|
||||
where: {
|
||||
id: session?.user?.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = {
|
||||
type: "apple_calendar",
|
||||
key: symmetricEncrypt(JSON.stringify({ username, password }), process.env.CALENDSO_ENCRYPTION_KEY!),
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
try {
|
||||
const dav = getCalendar({
|
||||
id: 0,
|
||||
...data,
|
||||
});
|
||||
await dav?.listCalendars();
|
||||
await prisma.credential.create({
|
||||
data,
|
||||
});
|
||||
} catch (reason) {
|
||||
logger.error("Could not add this caldav account", reason);
|
||||
return res.status(500).json({ message: "Could not add this caldav account" });
|
||||
}
|
||||
|
||||
return res.status(200).json({});
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { symmetricEncrypt } from "@lib/crypto";
|
||||
import { getCalendar } from "@lib/integrations/calendar/CalendarManager";
|
||||
import logger from "@lib/logger";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { username, password, url } = req.body;
|
||||
// Get user
|
||||
const user = await prisma.user.findFirst({
|
||||
rejectOnNotFound: true,
|
||||
where: {
|
||||
id: session?.user?.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = {
|
||||
type: "caldav_calendar",
|
||||
key: symmetricEncrypt(
|
||||
JSON.stringify({ username, password, url }),
|
||||
process.env.CALENDSO_ENCRYPTION_KEY!
|
||||
),
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
try {
|
||||
const dav = getCalendar({
|
||||
id: 0,
|
||||
...data,
|
||||
});
|
||||
await dav?.listCalendars();
|
||||
await prisma.credential.create({
|
||||
data,
|
||||
});
|
||||
} catch (reason) {
|
||||
logger.error("Could not add this caldav account", reason);
|
||||
return res.status(500).json({ message: "Could not add this caldav account" });
|
||||
}
|
||||
|
||||
return res.status(200).json({});
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { google } from "googleapis";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
|
||||
import { encodeOAuthState } from "../utils";
|
||||
|
||||
const credentials = process.env.GOOGLE_API_CREDENTIALS!;
|
||||
const scopes = [
|
||||
"https://www.googleapis.com/auth/calendar.readonly",
|
||||
"https://www.googleapis.com/auth/calendar.events",
|
||||
];
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
|
||||
if (!session) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get token from Google Calendar API
|
||||
const { client_secret, client_id } = JSON.parse(credentials).web;
|
||||
const redirect_uri = BASE_URL + "/api/integrations/googlecalendar/callback";
|
||||
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uri);
|
||||
|
||||
const authUrl = oAuth2Client.generateAuthUrl({
|
||||
access_type: "offline",
|
||||
scope: scopes,
|
||||
// A refresh token is only returned the first time the user
|
||||
// consents to providing access. For illustration purposes,
|
||||
// setting the prompt to 'consent' will force this consent
|
||||
// every time, forcing a refresh_token to be returned.
|
||||
prompt: "consent",
|
||||
state: encodeOAuthState(req),
|
||||
});
|
||||
|
||||
res.status(200).json({ url: authUrl });
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { google } from "googleapis";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { decodeOAuthState } from "../utils";
|
||||
|
||||
const credentials = process.env.GOOGLE_API_CREDENTIALS;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { code } = req.query;
|
||||
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
if (code && typeof code !== "string") {
|
||||
res.status(400).json({ message: "`code` must be a string" });
|
||||
return;
|
||||
}
|
||||
if (!credentials) {
|
||||
res.status(400).json({ message: "There are no Google Credentials installed." });
|
||||
return;
|
||||
}
|
||||
|
||||
const { client_secret, client_id } = JSON.parse(credentials).web;
|
||||
const redirect_uri = BASE_URL + "/api/integrations/googlecalendar/callback";
|
||||
|
||||
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uri);
|
||||
|
||||
let key = "";
|
||||
|
||||
if (code) {
|
||||
const token = await oAuth2Client.getToken(code);
|
||||
|
||||
key = token.res?.data;
|
||||
}
|
||||
|
||||
await prisma.credential.create({
|
||||
data: {
|
||||
type: "google_calendar",
|
||||
key,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
const state = decodeOAuthState(req);
|
||||
res.redirect(state?.returnTo ?? "/integrations");
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
|
||||
import { encodeOAuthState } from "../utils";
|
||||
|
||||
const scopes = ["User.Read", "Calendars.Read", "Calendars.ReadWrite", "offline_access"];
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const state = encodeOAuthState(req);
|
||||
const params = {
|
||||
response_type: "code",
|
||||
scope: scopes.join(" "),
|
||||
client_id: process.env.MS_GRAPH_CLIENT_ID,
|
||||
redirect_uri: BASE_URL + "/api/integrations/office365calendar/callback",
|
||||
state,
|
||||
};
|
||||
const query = stringify(params);
|
||||
const url = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${query}`;
|
||||
res.status(200).json({ url });
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
|
||||
import prisma from "../../../../lib/prisma";
|
||||
import { decodeOAuthState } from "../utils";
|
||||
|
||||
const scopes = ["offline_access", "Calendars.Read", "Calendars.ReadWrite"];
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { code } = req.query;
|
||||
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req: req });
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
if (typeof code !== "string") {
|
||||
res.status(400).json({ message: "No code returned" });
|
||||
return;
|
||||
}
|
||||
|
||||
const toUrlEncoded = (payload: Record<string, string>) =>
|
||||
Object.keys(payload)
|
||||
.map((key) => key + "=" + encodeURIComponent(payload[key]))
|
||||
.join("&");
|
||||
|
||||
const body = toUrlEncoded({
|
||||
client_id: process.env.MS_GRAPH_CLIENT_ID!,
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
scope: scopes.join(" "),
|
||||
redirect_uri: BASE_URL + "/api/integrations/office365calendar/callback",
|
||||
client_secret: process.env.MS_GRAPH_CLIENT_SECRET!,
|
||||
});
|
||||
|
||||
const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
const responseBody = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
return res.redirect("/integrations?error=" + JSON.stringify(responseBody));
|
||||
}
|
||||
|
||||
const whoami = await fetch("https://graph.microsoft.com/v1.0/me", {
|
||||
headers: { Authorization: "Bearer " + responseBody.access_token },
|
||||
});
|
||||
const graphUser = await whoami.json();
|
||||
|
||||
// In some cases, graphUser.mail is null. Then graphUser.userPrincipalName most likely contains the email address.
|
||||
responseBody.email = graphUser.mail ?? graphUser.userPrincipalName;
|
||||
responseBody.expiry_date = Math.round(+new Date() / 1000 + responseBody.expires_in); // set expiry date in seconds
|
||||
delete responseBody.expires_in;
|
||||
|
||||
await prisma.credential.create({
|
||||
data: {
|
||||
type: "office365_calendar",
|
||||
key: responseBody,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
const state = decodeOAuthState(req);
|
||||
return res.redirect(state?.returnTo ?? "/integrations");
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "@ee/pages/api/integrations/stripepayment/add";
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "@ee/pages/api/integrations/stripepayment/callback";
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "@ee/pages/api/integrations/stripepayment/portal";
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
const client_id = process.env.TANDEM_CLIENT_ID;
|
||||
const TANDEM_BASE_URL = process.env.TANDEM_BASE_URL;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get user
|
||||
await prisma.user.findFirst({
|
||||
rejectOnNotFound: true,
|
||||
where: {
|
||||
id: session?.user?.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
const redirect_uri = encodeURI(BASE_URL + "/api/integrations/tandemvideo/callback");
|
||||
|
||||
const params = {
|
||||
client_id,
|
||||
redirect_uri,
|
||||
};
|
||||
const query = stringify(params);
|
||||
const url = `${TANDEM_BASE_URL}/oauth/approval?${query}`;
|
||||
res.status(200).json({ url });
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
const client_id = process.env.TANDEM_CLIENT_ID as string;
|
||||
const client_secret = process.env.TANDEM_CLIENT_SECRET as string;
|
||||
const TANDEM_BASE_URL = (process.env.TANDEM_BASE_URL as string) || "https://tandem.chat";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (!req.query.code) {
|
||||
res.status(401).json({ message: "Missing code" });
|
||||
return;
|
||||
}
|
||||
|
||||
const code = req.query.code as string;
|
||||
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await fetch(`${TANDEM_BASE_URL}/api/v1/oauth/v2/token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ code, client_id, client_secret }),
|
||||
});
|
||||
|
||||
const responseBody = await result.json();
|
||||
|
||||
if (result.ok) {
|
||||
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
|
||||
delete responseBody.expires_in;
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
data: {
|
||||
credentials: {
|
||||
create: {
|
||||
type: "tandem_video",
|
||||
key: responseBody,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
res.redirect("/integrations");
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
export type IntegrationOAuthCallbackState = {
|
||||
returnTo: string;
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
import { NextApiRequest } from "next";
|
||||
|
||||
import { IntegrationOAuthCallbackState } from "./types";
|
||||
|
||||
export function encodeOAuthState(req: NextApiRequest) {
|
||||
if (typeof req.query.state !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const state: IntegrationOAuthCallbackState = JSON.parse(req.query.state);
|
||||
|
||||
return JSON.stringify(state);
|
||||
}
|
||||
|
||||
export function decodeOAuthState(req: NextApiRequest) {
|
||||
if (typeof req.query.state !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const state: IntegrationOAuthCallbackState = JSON.parse(req.query.state);
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { stringify } from "querystring";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
const client_id = process.env.ZOOM_CLIENT_ID;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Get user
|
||||
await prisma.user.findFirst({
|
||||
rejectOnNotFound: true,
|
||||
where: {
|
||||
id: session?.user?.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id,
|
||||
redirect_uri: BASE_URL + "/api/integrations/zoomvideo/callback",
|
||||
};
|
||||
const query = stringify(params);
|
||||
const url = `https://zoom.us/oauth/authorize?${query}`;
|
||||
res.status(200).json({ url });
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { getSession } from "@lib/auth";
|
||||
import { BASE_URL } from "@lib/config/constants";
|
||||
|
||||
import prisma from "../../../../lib/prisma";
|
||||
|
||||
const client_id = process.env.ZOOM_CLIENT_ID;
|
||||
const client_secret = process.env.ZOOM_CLIENT_SECRET;
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { code } = req.query;
|
||||
|
||||
// Check that user is authenticated
|
||||
const session = await getSession({ req });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
res.status(401).json({ message: "You must be logged in to do this" });
|
||||
return;
|
||||
}
|
||||
|
||||
const redirectUri = encodeURI(BASE_URL + "/api/integrations/zoomvideo/callback");
|
||||
const authHeader = "Basic " + Buffer.from(client_id + ":" + client_secret).toString("base64");
|
||||
const result = await fetch(
|
||||
"https://zoom.us/oauth/token?grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUri,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const responseBody = await result.json();
|
||||
|
||||
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
|
||||
delete responseBody.expires_in;
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
data: {
|
||||
credentials: {
|
||||
create: {
|
||||
type: "zoom_video",
|
||||
key: responseBody,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
res.redirect("/integrations");
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { GetStaticPaths, GetStaticPathsResult, GetStaticPropsContext } from "next";
|
||||
|
||||
import { getAppRegistry } from "@calcom/app-store/_appRegistry";
|
||||
|
||||
import { inferSSRProps } from "@lib/types/inferSSRProps";
|
||||
|
||||
import App from "@components/App";
|
||||
|
||||
function SingleAppPage({ data }: inferSSRProps<typeof getStaticProps>) {
|
||||
return (
|
||||
<App
|
||||
name={data.name}
|
||||
isGlobal={data.isGlobal}
|
||||
type={data.type}
|
||||
logo={data.logo}
|
||||
categories={[data.category]}
|
||||
author="Cal.com"
|
||||
feeType={data.feeType || "usage-based"}
|
||||
price={data.price || 0}
|
||||
commission={data.commission || 0}
|
||||
docs={data.docsUrl}
|
||||
website={data.url}
|
||||
email={data.email}
|
||||
// tos="https://zoom.us/terms"
|
||||
// privacy="https://zoom.us/privacy"
|
||||
body={data.description}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
|
||||
const appStore = getAppRegistry();
|
||||
const paths = appStore.reduce((paths, app) => {
|
||||
paths.push({ params: { slug: app.slug } });
|
||||
return paths;
|
||||
}, [] as GetStaticPathsResult<{ slug: string }>["paths"]);
|
||||
|
||||
return {
|
||||
paths,
|
||||
fallback: false,
|
||||
};
|
||||
};
|
||||
|
||||
export const getStaticProps = async (ctx: GetStaticPropsContext) => {
|
||||
const appStore = getAppRegistry();
|
||||
|
||||
if (typeof ctx.params?.slug !== "string") {
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
const singleApp = appStore.find((app) => app.slug === ctx.params?.slug);
|
||||
|
||||
if (!singleApp) {
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
data: singleApp,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default SingleAppPage;
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ChevronLeftIcon } from "@heroicons/react/solid";
|
||||
import { InferGetStaticPropsType } from "next";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { getAppRegistry } from "@calcom/app-store/_appRegistry";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import Button from "@calcom/ui/Button";
|
||||
|
||||
import Shell from "@components/Shell";
|
||||
import AppCard from "@components/apps/AppCard";
|
||||
|
||||
export default function Apps({ appStore }: InferGetStaticPropsType<typeof getStaticProps>) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<Shell
|
||||
heading={router.query.category + " - " + t("app_store")}
|
||||
subtitle={t("app_store_description")}
|
||||
large>
|
||||
<div className="mb-8">
|
||||
<Button color="secondary" href="/apps">
|
||||
<ChevronLeftIcon className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mb-16">
|
||||
<h2 className="mb-2 text-lg font-semibold text-gray-900">All {router.query.category} apps</h2>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{appStore.map((app) => {
|
||||
return (
|
||||
app.category === router.query.category && (
|
||||
<AppCard
|
||||
key={app.name}
|
||||
slug={app.slug}
|
||||
name={app.name}
|
||||
description={app.description}
|
||||
logo={app.logo}
|
||||
rating={app.rating}
|
||||
/>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
export const getStaticPaths = async () => {
|
||||
const appStore = getAppRegistry();
|
||||
const paths = appStore.reduce((categories, app) => {
|
||||
if (!categories.includes(app.category)) {
|
||||
categories.push(app.category);
|
||||
}
|
||||
return categories;
|
||||
}, [] as string[]);
|
||||
|
||||
return {
|
||||
paths: paths.map((category) => ({ params: { category } })),
|
||||
fallback: false,
|
||||
};
|
||||
};
|
||||
|
||||
export const getStaticProps = async () => {
|
||||
return {
|
||||
props: {
|
||||
appStore: getAppRegistry(),
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { InferGetStaticPropsType } from "next";
|
||||
|
||||
import { getAppRegistry } from "@calcom/app-store/_appRegistry";
|
||||
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
|
||||
import AppsShell from "@components/AppsShell";
|
||||
import Shell from "@components/Shell";
|
||||
import AllApps from "@components/apps/AllApps";
|
||||
import AppStoreCategories from "@components/apps/Categories";
|
||||
import Slider from "@components/apps/Slider";
|
||||
|
||||
export default function Apps({ appStore, categories }: InferGetStaticPropsType<typeof getStaticProps>) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<Shell heading={t("app_store")} subtitle={t("app_store_description")} large>
|
||||
<AppsShell>
|
||||
<AppStoreCategories categories={categories} />
|
||||
<Slider items={appStore} />
|
||||
<AllApps apps={appStore} />
|
||||
</AppsShell>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
export const getStaticProps = async () => {
|
||||
const appStore = getAppRegistry();
|
||||
const categories = appStore.reduce((c, app) => {
|
||||
c[app.category] = c[app.category] ? c[app.category] + 1 : 1;
|
||||
return c;
|
||||
}, {} as Record<string, number>);
|
||||
|
||||
return {
|
||||
props: {
|
||||
categories: Object.entries(categories).map(([name, count]) => ({ name, count })),
|
||||
appStore,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -3,7 +3,9 @@ import Image from "next/image";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { JSONObject } from "superjson/dist/types";
|
||||
|
||||
import { InstallAppButton } from "@calcom/app-store/components";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { App } from "@calcom/types/App";
|
||||
import { Alert } from "@calcom/ui/Alert";
|
||||
import Button from "@calcom/ui/Button";
|
||||
|
||||
@@ -18,7 +20,6 @@ import { List, ListItem, ListItemText, ListItemTitle } from "@components/List";
|
||||
import Loader from "@components/Loader";
|
||||
import Shell, { ShellSubHeading } from "@components/Shell";
|
||||
import { CalendarListContainer } from "@components/integrations/CalendarListContainer";
|
||||
import ConnectIntegration from "@components/integrations/ConnectIntegrations";
|
||||
import DisconnectIntegration from "@components/integrations/DisconnectIntegration";
|
||||
import IntegrationListItem from "@components/integrations/IntegrationListItem";
|
||||
import SubHeadingTitleWithConnections from "@components/integrations/SubHeadingTitleWithConnections";
|
||||
@@ -41,7 +42,7 @@ function IframeEmbedContainer() {
|
||||
<List>
|
||||
<ListItem className={classNames("flex-col")}>
|
||||
<div className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
|
||||
<Image width={40} height={40} src="/integrations/embed.svg" alt="Embed" />
|
||||
<Image width={40} height={40} src="/apps/embed.svg" alt="Embed" />
|
||||
<div className="flex-grow truncate pl-2">
|
||||
<ListItemTitle component="h3">{t("standard_iframe")}</ListItemTitle>
|
||||
<ListItemText component="p">{t("embed_your_calendar")}</ListItemText>
|
||||
@@ -66,7 +67,7 @@ function IframeEmbedContainer() {
|
||||
</ListItem>
|
||||
<ListItem className={classNames("flex-col")}>
|
||||
<div className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
|
||||
<Image width={40} height={40} src="/integrations/embed.svg" alt="Embed" />
|
||||
<Image width={40} height={40} src="/apps/embed.svg" alt="Embed" />
|
||||
<div className="flex-grow truncate pl-2">
|
||||
<ListItemTitle component="h3">{t("responsive_fullscreen_iframe")}</ListItemTitle>
|
||||
<ListItemText component="p">A fullscreen scheduling experience on your website</ListItemText>
|
||||
@@ -108,7 +109,8 @@ function IframeEmbedContainer() {
|
||||
function ConnectOrDisconnectIntegrationButton(props: {
|
||||
//
|
||||
credentialIds: number[];
|
||||
type: string;
|
||||
type: App["type"];
|
||||
isGlobal?: boolean;
|
||||
installed: boolean;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
@@ -139,7 +141,7 @@ function ConnectOrDisconnectIntegrationButton(props: {
|
||||
);
|
||||
}
|
||||
/** We don't need to "Connect", just show that it's installed */
|
||||
if (["daily_video", "huddle01_video", "jitsi_video"].includes(props.type)) {
|
||||
if (props.isGlobal) {
|
||||
return (
|
||||
<div className="truncate px-3 py-2">
|
||||
<h3 className="text-sm font-medium text-gray-700">{t("installed")}</h3>
|
||||
@@ -147,14 +149,14 @@ function ConnectOrDisconnectIntegrationButton(props: {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ConnectIntegration
|
||||
<InstallAppButton
|
||||
type={props.type}
|
||||
render={(btnProps) => (
|
||||
<Button color="secondary" {...btnProps} data-testid="integration-connection-button">
|
||||
render={(buttonProps) => (
|
||||
<Button color="secondary" {...buttonProps} data-testid="integration-connection-button">
|
||||
{t("connect")}
|
||||
</Button>
|
||||
)}
|
||||
onOpenChange={handleOpenChange}
|
||||
onChanged={handleOpenChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -179,8 +181,17 @@ function IntegrationsContainer() {
|
||||
{data.conferencing.items.map((item) => (
|
||||
<IntegrationListItem
|
||||
key={item.title}
|
||||
{...item}
|
||||
actions={<ConnectOrDisconnectIntegrationButton {...item} />}
|
||||
title={item.title}
|
||||
imageSrc={item.imageSrc}
|
||||
description={item.description}
|
||||
actions={
|
||||
<ConnectOrDisconnectIntegrationButton
|
||||
credentialIds={item.credentialIds}
|
||||
type={item.type}
|
||||
isGlobal={item.isGlobal}
|
||||
installed={item.installed}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
@@ -195,8 +206,17 @@ function IntegrationsContainer() {
|
||||
{data.payment.items.map((item) => (
|
||||
<IntegrationListItem
|
||||
key={item.title}
|
||||
{...item}
|
||||
actions={<ConnectOrDisconnectIntegrationButton {...item} />}
|
||||
imageSrc={item.imageSrc}
|
||||
title={item.title}
|
||||
description={item.description}
|
||||
actions={
|
||||
<ConnectOrDisconnectIntegrationButton
|
||||
credentialIds={item.credentialIds}
|
||||
type={item.type}
|
||||
isGlobal={item.isGlobal}
|
||||
installed={item.installed}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
@@ -215,7 +235,7 @@ function Web3Container() {
|
||||
<List>
|
||||
<ListItem className={classNames("flex-col")}>
|
||||
<div className={classNames("flex w-full flex-1 items-center space-x-2 p-3")}>
|
||||
<Image width={40} height={40} src="/integrations/metamask.svg" alt="Embed" />
|
||||
<Image width={40} height={40} src="/apps/metamask.svg" alt="Embed" />
|
||||
<div className="flex-grow truncate pl-2">
|
||||
<ListItemTitle component="h3">
|
||||
MetaMask (
|
||||
@@ -286,7 +306,7 @@ export default function IntegrationsPage() {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<Shell heading={t("integrations")} subtitle={t("connect_your_favourite_apps")}>
|
||||
<Shell heading={t("installed_apps")} subtitle={t("manage_your_connected_apps")}>
|
||||
<ClientSuspense fallback={<Loader />}>
|
||||
<IntegrationsContainer />
|
||||
<CalendarListContainer />
|
||||
@@ -0,0 +1,118 @@
|
||||
import showToast from "@calcom/lib/notification";
|
||||
|
||||
import App from "@components/App";
|
||||
|
||||
export default function NukeMyCal() {
|
||||
return (
|
||||
<App
|
||||
name="Wipe my Cal"
|
||||
type="wipemycal_other"
|
||||
logo="/apps/nuke-my-cal.svg"
|
||||
categories={["fun", "productivity"]}
|
||||
author="/peer"
|
||||
feeType="free" // "usage-based", "monthly", "one-time" or "free"
|
||||
price={0} // 0 = free. if type="usage-based" it's the price per booking
|
||||
commission={0} // only required for "usage-based" billing. % of commission for paid bookings
|
||||
website="https://cal.com"
|
||||
email="[email protected]"
|
||||
tos="https://cal.com/terms"
|
||||
privacy="https://cal.com/privacy"
|
||||
body={
|
||||
<>
|
||||
<style jsx>
|
||||
{`
|
||||
.pushable {
|
||||
position: relative;
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
outline-offset: 4px;
|
||||
transition: filter 250ms;
|
||||
}
|
||||
.shadow {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 12px;
|
||||
background: hsl(0deg 0% 0% / 0.25);
|
||||
will-change: transform;
|
||||
transform: translateY(2px);
|
||||
transition: transform 600ms cubic-bezier(0.3, 0.7, 0.4, 1);
|
||||
}
|
||||
.edge {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(
|
||||
to left,
|
||||
hsl(340deg 100% 16%) 0%,
|
||||
hsl(340deg 100% 32%) 8%,
|
||||
hsl(340deg 100% 32%) 92%,
|
||||
hsl(340deg 100% 16%) 100%
|
||||
);
|
||||
}
|
||||
.front {
|
||||
display: block;
|
||||
position: relative;
|
||||
padding: 12px 42px;
|
||||
border-radius: 12px;
|
||||
font-size: 1.25rem;
|
||||
color: white;
|
||||
background: hsl(345deg 100% 47%);
|
||||
will-change: transform;
|
||||
transform: translateY(-4px);
|
||||
transition: transform 600ms cubic-bezier(0.3, 0.7, 0.4, 1);
|
||||
}
|
||||
.pushable:hover {
|
||||
filter: brightness(110%);
|
||||
}
|
||||
.pushable:hover .front {
|
||||
transform: translateY(-6px);
|
||||
transition: transform 250ms cubic-bezier(0.3, 0.7, 0.4, 1.5);
|
||||
}
|
||||
.pushable:active .front {
|
||||
transform: translateY(-2px);
|
||||
transition: transform 34ms;
|
||||
}
|
||||
.pushable:hover .shadow {
|
||||
transform: translateY(4px);
|
||||
transition: transform 250ms cubic-bezier(0.3, 0.7, 0.4, 1.5);
|
||||
}
|
||||
.pushable:active .shadow {
|
||||
transform: translateY(1px);
|
||||
transition: transform 34ms;
|
||||
}
|
||||
.pushable:focus:not(:focus-visible) {
|
||||
outline: none;
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
<div>
|
||||
Have an emergency? Need to reschedule all of your upcoming calendar events? Just click{" "}
|
||||
<strong>Nuke my Cal</strong> and auto-reschedule the entire day. Give it a try!
|
||||
<br />
|
||||
<br />
|
||||
Demo: <br />
|
||||
<br />
|
||||
</div>
|
||||
<button
|
||||
onClick={() => (
|
||||
new Audio("/apps/nuke-my-cal.wav").play(),
|
||||
showToast("All of your calendar events for today have been rescheduled", "success")
|
||||
)}
|
||||
className="pushable">
|
||||
<span className="shadow"></span>
|
||||
<span className="edge"></span>
|
||||
<span className="front">Nuke my Cal</span>
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -13,8 +13,7 @@ import {
|
||||
UsersIcon,
|
||||
} from "@heroicons/react/solid";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { MembershipRole } from "@prisma/client";
|
||||
import { EventTypeCustomInput, PeriodType, Prisma, SchedulingType } from "@prisma/client";
|
||||
import { EventTypeCustomInput, MembershipRole, PeriodType, Prisma, SchedulingType } from "@prisma/client";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
|
||||
import * as RadioGroup from "@radix-ui/react-radio-group";
|
||||
import classNames from "classnames";
|
||||
@@ -30,6 +29,7 @@ import Select, { Props as SelectProps } from "react-select";
|
||||
import { JSONObject } from "superjson/dist/types";
|
||||
import { z } from "zod";
|
||||
|
||||
import getApps, { getLocationOptions, hasIntegration } from "@calcom/app-store/utils";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { StripeData } from "@calcom/stripe/server";
|
||||
import Button from "@calcom/ui/Button";
|
||||
@@ -42,7 +42,6 @@ import { asStringOrThrow, asStringOrUndefined } from "@lib/asStringOrNull";
|
||||
import { getSession } from "@lib/auth";
|
||||
import { HttpError } from "@lib/core/http/error";
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
import getIntegrations, { hasIntegration } from "@lib/integrations/getIntegrations";
|
||||
import { LocationType } from "@lib/location";
|
||||
import prisma from "@lib/prisma";
|
||||
import { slugify } from "@lib/slugify";
|
||||
@@ -346,6 +345,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
|
||||
);
|
||||
case LocationType.Phone:
|
||||
return <p className="text-sm">{t("cal_invitee_phone_number_scheduling")}</p>;
|
||||
/* TODO: Render this dynamically from App Store */
|
||||
case LocationType.GoogleMeet:
|
||||
return <p className="text-sm">{t("cal_provide_google_meet_location")}</p>;
|
||||
case LocationType.Zoom:
|
||||
@@ -358,6 +358,8 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
|
||||
return <p className="text-sm">{t("cal_provide_huddle01_meeting_url")}</p>;
|
||||
case LocationType.Tandem:
|
||||
return <p className="text-sm">{t("cal_provide_tandem_meeting_url")}</p>;
|
||||
case LocationType.Teams:
|
||||
return <p className="text-sm">{t("cal_provide_teams_meeting_url")}</p>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -701,6 +703,78 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
|
||||
<span className="ml-2 text-sm">Jitsi Meet</span>
|
||||
</div>
|
||||
)}
|
||||
{location.type === LocationType.Teams && (
|
||||
<div className="flex flex-grow items-center">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-6 w-6"
|
||||
viewBox="0 0 2228.833 2073.333">
|
||||
<path
|
||||
fill="#5059C9"
|
||||
d="M1554.637,777.5h575.713c54.391,0,98.483,44.092,98.483,98.483c0,0,0,0,0,0v524.398 c0,199.901-162.051,361.952-361.952,361.952h0h-1.711c-199.901,0.028-361.975-162-362.004-361.901c0-0.017,0-0.034,0-0.052V828.971 C1503.167,800.544,1526.211,777.5,1554.637,777.5L1554.637,777.5z"
|
||||
/>
|
||||
<circle fill="#5059C9" cx="1943.75" cy="440.583" r="233.25" />
|
||||
<circle fill="#7B83EB" cx="1218.083" cy="336.917" r="336.917" />
|
||||
<path
|
||||
fill="#7B83EB"
|
||||
d="M1667.323,777.5H717.01c-53.743,1.33-96.257,45.931-95.01,99.676v598.105 c-7.505,322.519,247.657,590.16,570.167,598.053c322.51-7.893,577.671-275.534,570.167-598.053V877.176 C1763.579,823.431,1721.066,778.83,1667.323,777.5z"
|
||||
/>
|
||||
<path
|
||||
opacity=".1"
|
||||
d="M1244,777.5v838.145c-0.258,38.435-23.549,72.964-59.09,87.598 c-11.316,4.787-23.478,7.254-35.765,7.257H667.613c-6.738-17.105-12.958-34.21-18.142-51.833 c-18.144-59.477-27.402-121.307-27.472-183.49V877.02c-1.246-53.659,41.198-98.19,94.855-99.52H1244z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1192.167,777.5v889.978c-0.002,12.287-2.47,24.449-7.257,35.765 c-14.634,35.541-49.163,58.833-87.598,59.09H691.975c-8.812-17.105-17.105-34.21-24.362-51.833 c-7.257-17.623-12.958-34.21-18.142-51.833c-18.144-59.476-27.402-121.307-27.472-183.49V877.02 c-1.246-53.659,41.198-98.19,94.855-99.52H1192.167z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1192.167,777.5v786.312c-0.395,52.223-42.632,94.46-94.855,94.855h-447.84 c-18.144-59.476-27.402-121.307-27.472-183.49V877.02c-1.246-53.659,41.198-98.19,94.855-99.52H1192.167z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1140.333,777.5v786.312c-0.395,52.223-42.632,94.46-94.855,94.855H649.472 c-18.144-59.476-27.402-121.307-27.472-183.49V877.02c-1.246-53.659,41.198-98.19,94.855-99.52H1140.333z"
|
||||
/>
|
||||
<path
|
||||
opacity=".1"
|
||||
d="M1244,509.522v163.275c-8.812,0.518-17.105,1.037-25.917,1.037 c-8.812,0-17.105-0.518-25.917-1.037c-17.496-1.161-34.848-3.937-51.833-8.293c-104.963-24.857-191.679-98.469-233.25-198.003 c-7.153-16.715-12.706-34.071-16.587-51.833h258.648C1201.449,414.866,1243.801,457.217,1244,509.522z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1192.167,561.355v111.442c-17.496-1.161-34.848-3.937-51.833-8.293 c-104.963-24.857-191.679-98.469-233.25-198.003h190.228C1149.616,466.699,1191.968,509.051,1192.167,561.355z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1192.167,561.355v111.442c-17.496-1.161-34.848-3.937-51.833-8.293 c-104.963-24.857-191.679-98.469-233.25-198.003h190.228C1149.616,466.699,1191.968,509.051,1192.167,561.355z"
|
||||
/>
|
||||
<path
|
||||
opacity=".2"
|
||||
d="M1140.333,561.355v103.148c-104.963-24.857-191.679-98.469-233.25-198.003 h138.395C1097.783,466.699,1140.134,509.051,1140.333,561.355z"
|
||||
/>
|
||||
<linearGradient
|
||||
id="a"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="198.099"
|
||||
y1="1683.0726"
|
||||
x2="942.2344"
|
||||
y2="394.2607"
|
||||
gradientTransform="matrix(1 0 0 -1 0 2075.3333)">
|
||||
<stop offset="0" stopColor="#5a62c3" />
|
||||
<stop offset=".5" stopColor="#4d55bd" />
|
||||
<stop offset="1" stopColor="#3940ab" />
|
||||
</linearGradient>
|
||||
<path
|
||||
fill="url(#a)"
|
||||
d="M95.01,466.5h950.312c52.473,0,95.01,42.538,95.01,95.01v950.312c0,52.473-42.538,95.01-95.01,95.01 H95.01c-52.473,0-95.01-42.538-95.01-95.01V561.51C0,509.038,42.538,466.5,95.01,466.5z"
|
||||
/>
|
||||
<path
|
||||
fill="#FFF"
|
||||
d="M820.211,828.193H630.241v517.297H509.211V828.193H320.123V727.844h500.088V828.193z"
|
||||
/>
|
||||
</svg>
|
||||
<span className="ml-2 text-sm">MS Teams</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex">
|
||||
<button
|
||||
type="button"
|
||||
@@ -725,7 +799,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
className="flex rounded-sm py-2 hover:bg-gray-100"
|
||||
className="flex rounded-sm py-2 hover:bg-gray-100"
|
||||
onClick={() => setShowLocationModal(true)}>
|
||||
<PlusIcon className="mt-0.5 h-4 w-4 text-neutral-900" />
|
||||
<span className="ml-1 text-sm font-medium text-neutral-700">{t("add_location")}</span>
|
||||
@@ -1529,7 +1603,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
<div className="m-0 mb-4 mt-0 w-full lg:w-3/12 lg:px-2 lg:ltr:ml-2 lg:rtl:mr-2">
|
||||
<div className="m-0 mt-0 mb-4 w-full lg:w-3/12 lg:px-2 lg:ltr:ml-2 lg:rtl:mr-2">
|
||||
<div className="px-2">
|
||||
<Controller
|
||||
name="hidden"
|
||||
@@ -1845,6 +1919,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1872,17 +1947,9 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
eventType.users.push(fallbackUser);
|
||||
}
|
||||
|
||||
const integrations = getIntegrations(credentials);
|
||||
const integrations = getApps(credentials);
|
||||
const locationOptions = getLocationOptions(integrations);
|
||||
|
||||
const locationOptions: OptionTypeBase[] = [];
|
||||
|
||||
if (hasIntegration(integrations, "zoom_video")) {
|
||||
locationOptions.push({
|
||||
value: LocationType.Zoom,
|
||||
label: "Zoom Video",
|
||||
disabled: true,
|
||||
});
|
||||
}
|
||||
const hasPaymentIntegration = hasIntegration(integrations, "stripe_payment");
|
||||
if (hasIntegration(integrations, "google_calendar")) {
|
||||
locationOptions.push({
|
||||
@@ -1890,27 +1957,6 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
|
||||
label: "Google Meet",
|
||||
});
|
||||
}
|
||||
if (hasIntegration(integrations, "daily_video")) {
|
||||
locationOptions.push({
|
||||
value: LocationType.Daily,
|
||||
label: "Daily.co Video",
|
||||
});
|
||||
}
|
||||
if (hasIntegration(integrations, "jitsi_video")) {
|
||||
locationOptions.push({
|
||||
value: LocationType.Jitsi,
|
||||
label: "Jitsi Meet",
|
||||
});
|
||||
}
|
||||
if (hasIntegration(integrations, "huddle01_video")) {
|
||||
locationOptions.push({
|
||||
value: LocationType.Huddle01,
|
||||
label: "Huddle01 Video",
|
||||
});
|
||||
}
|
||||
if (hasIntegration(integrations, "tandem_video")) {
|
||||
locationOptions.push({ value: LocationType.Tandem, label: "Tandem Video" });
|
||||
}
|
||||
const currency =
|
||||
(credentials.find((integration) => integration.type === "stripe_payment")?.key as unknown as StripeData)
|
||||
?.default_currency || "usd";
|
||||
|
||||
@@ -17,6 +17,8 @@ import { useForm } from "react-hook-form";
|
||||
import TimezoneSelect from "react-timezone-select";
|
||||
import * as z from "zod";
|
||||
|
||||
import getApps from "@calcom/app-store/utils";
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import { Alert } from "@calcom/ui/Alert";
|
||||
import Button from "@calcom/ui/Button";
|
||||
import { Form } from "@calcom/ui/form/fields";
|
||||
@@ -25,8 +27,6 @@ import { asStringOrNull } from "@lib/asStringOrNull";
|
||||
import { getSession } from "@lib/auth";
|
||||
import { DEFAULT_SCHEDULE } from "@lib/availability";
|
||||
import { useLocale } from "@lib/hooks/useLocale";
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@lib/integrations/calendar/CalendarManager";
|
||||
import getIntegrations from "@lib/integrations/getIntegrations";
|
||||
import prisma from "@lib/prisma";
|
||||
import { collectPageParameters, telemetryEventTypes, useTelemetry } from "@lib/telemetry";
|
||||
import { trpc } from "@lib/trpc";
|
||||
@@ -676,10 +676,11 @@ export async function getServerSideProps(context: NextPageContext) {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const integrations = getIntegrations(credentials)
|
||||
const integrations = getApps(credentials)
|
||||
.filter((item) => item.type.endsWith("_calendar"))
|
||||
.map((item) => omit(item, "key"));
|
||||
|
||||
|
||||
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user