Skip to content

The open alternative to Salesforce, designed for AI.

1.4 KB
Raw Blame
import { isUndefined } from '@sniptt/guards';
import { isNonEmptyString } from 'src/logic-functions/utils/isNonEmptyString';

type ComputeRealMeetingKeyInput = {
  calendarEventId: string;
  conferenceLinkUrl: unknown;
  iCalUid: string | undefined;
  startsAt: string | undefined;
};

export const computeRealMeetingKey = ({
  calendarEventId,
  conferenceLinkUrl,
  iCalUid,
  startsAt,
}: ComputeRealMeetingKeyInput): string => {
  const normalizedConferenceLink = normalizeConferenceLink(conferenceLinkUrl);

  if (!isUndefined(normalizedConferenceLink)) {
    return `link:${normalizedConferenceLink}:${startsAt ?? ''}`;
  }

  if (isNonEmptyString(iCalUid)) {
    return `ical:${iCalUid}:${startsAt ?? ''}`;
  }

  return `event:${calendarEventId}`;
};

const normalizeConferenceLink = (
  conferenceLinkUrl: unknown,
): string | undefined => {
  if (!isNonEmptyString(conferenceLinkUrl)) {
    return undefined;
  }

  const withoutProtocol = conferenceLinkUrl
    .trim()
    .toLowerCase()
    .replace(/^https?:\/\//, '')
    .replace(/^www\./, '');

  const withoutQueryAndFragment = withoutProtocol.split(/[?#]/)[0];
  const meetingToken = new URLSearchParams(
    withoutProtocol.split('?')[1]?.split('#')[0],
  ).get('mtid');
  const withoutTrailingSlash = withoutQueryAndFragment.replace(/\/+$/, '');

  return withoutTrailingSlash === ''
    ? undefined
    : `${withoutTrailingSlash}${meetingToken ? `?mtid=${meetingToken}` : ''}`;
};