Files
calendar/apps/web/app/api/logo/route.ts
T
8ad442f2be feat: Upgrade to Next 15 (#18834)
* wip

* update layoutHOC

* wip

* remove app router related code no longer used

* remove more

* await cookies, headers, params, serachparams

* update yarn.lock

* await cookies, headers, params, serachparams more

* update yarn lock again

* downgrade next-auth to 4.22.1

* update yarn lock

* fix

* update yarn lock

* fix type checks

* update yarn lock

* await headers and cookies

* restore pages folder

* restore yarn.lock

* update yarn.lock

* await headers and cookies

* remove

* await params in API routes

* updates

* restore next.config.js

* remove i18n from next.config.js

* Fixed tests

* Fixed types

* Removed duplicate favicon.ico

* Fixing more types

* ImageResponse moved to next/og

* Fixed prisma import issues

* dynamic import for @ewsjs/xhr

* remove deasync dep

* dynamic import for @tryvital/vital-node

* fix type checks

* add back turbopack command

* Type fix

* Removed unneeded file

* fix turbopack relative path errors

* add comments

* remove unneeded code

* Fixed build errors

* await apis

* use Promise<Params> type in defaultResponderForAppDir util

* refactor scim api route

* fix type checks

* separate app-routing.config into client-config and server-config

* wip

* refactor routing forms components

* revert unneeded changes for easier review

* fix

* fix

* use CustomTrans

* fix type

* fix unit tests

* fix type error

* fix build error

* fix build error

* fix build error

* fix warnings

* fix warnings

* upgrade @tremor/react and tailwindcss

* numCols -> numItems

* fix forgot-password e2e test

* fix 1 more e2e test

* fix login e2e test

* fix e2e tests

* fix e2e tests

* clean up

* remove error

* use tremor/react 2.11.0

* fix

* rename CustomTrans to ServerTrans

* address comment

* fix test

* fix ServerTrans

* fix

* fix type

* fix ServerTrans usages 1

* fix translations

* fix type checks

* fix type checks

* link styling

* fix

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-03-20 21:30:51 -03:00

223 lines
5.9 KiB
TypeScript

import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
import { cookies, headers } from "next/headers";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { z } from "zod";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import {
ANDROID_CHROME_ICON_192,
ANDROID_CHROME_ICON_256,
APPLE_TOUCH_ICON,
FAVICON_16,
FAVICON_32,
IS_SELF_HOSTED,
LOGO,
LOGO_ICON,
MSTILE_ICON,
WEBAPP_URL,
} from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
const log = logger.getSubLogger({ prefix: ["[api/logo]"] });
function removePort(url: string) {
return url.replace(/:\d+$/, "");
}
function extractSubdomainAndDomain(hostname: string) {
const hostParts = removePort(hostname).split(".");
const subdomainParts = hostParts.slice(0, hostParts.length - 2);
const domain = hostParts.slice(hostParts.length - 2).join(".");
return [subdomainParts[0], domain];
}
const logoApiSchema = z.object({
type: z.coerce.string().optional(),
});
const SYSTEM_SUBDOMAINS = ["console", "app", "www"];
type LogoType =
| "logo"
| "icon"
| "favicon-16"
| "favicon-32"
| "apple-touch-icon"
| "mstile"
| "android-chrome-192"
| "android-chrome-256";
type LogoTypeDefinition = {
fallback: string;
w?: number;
h?: number;
source: "appLogo" | "appIconLogo";
};
const logoDefinitions: Record<LogoType, LogoTypeDefinition> = {
logo: {
fallback: `${WEBAPP_URL}${LOGO}`,
source: "appLogo",
},
icon: {
fallback: `${WEBAPP_URL}${LOGO_ICON}`,
source: "appIconLogo",
},
"favicon-16": {
fallback: `${WEBAPP_URL}${FAVICON_16}`,
w: 16,
h: 16,
source: "appIconLogo",
},
"favicon-32": {
fallback: `${WEBAPP_URL}${FAVICON_32}`,
w: 32,
h: 32,
source: "appIconLogo",
},
"apple-touch-icon": {
fallback: `${WEBAPP_URL}${APPLE_TOUCH_ICON}`,
w: 180,
h: 180,
source: "appLogo",
},
mstile: {
fallback: `${WEBAPP_URL}${MSTILE_ICON}`,
w: 150,
h: 150,
source: "appLogo",
},
"android-chrome-192": {
fallback: `${WEBAPP_URL}${ANDROID_CHROME_ICON_192}`,
w: 192,
h: 192,
source: "appLogo",
},
"android-chrome-256": {
fallback: `${WEBAPP_URL}${ANDROID_CHROME_ICON_256}`,
w: 256,
h: 256,
source: "appLogo",
},
};
function isValidLogoType(type: string): type is LogoType {
return type in logoDefinitions;
}
async function getTeamLogos(subdomain: string, isValidOrgDomain: boolean) {
try {
if (
// if not cal.com
IS_SELF_HOSTED ||
// missing subdomain (empty string)
!subdomain ||
// in SYSTEM_SUBDOMAINS list
SYSTEM_SUBDOMAINS.includes(subdomain)
) {
throw new Error("No custom logo needed");
}
// load from DB
const { default: prisma } = await import("@calcom/prisma");
const team = await prisma.team.findFirst({
where: {
slug: subdomain,
...(isValidOrgDomain && {
OR: [
{
metadata: {
path: ["isOrganization"],
equals: true,
},
},
{
isOrganization: true,
},
],
}),
},
select: {
appLogo: true,
appIconLogo: true,
},
});
return {
appLogo: team?.appLogo,
appIconLogo: team?.appIconLogo,
};
} catch (error) {
if (error instanceof Error) log.debug(error.message);
return {
appLogo: undefined,
appIconLogo: undefined,
};
}
}
/**
* This API endpoint is used to serve the logo associated with a team if no logo is found we serve our default logo
*/
async function getHandler(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const parsedQuery = logoApiSchema.parse(Object.fromEntries(searchParams.entries()));
// Create a legacy request object for compatibility
const legacyReq = buildLegacyRequest(await headers(), await cookies());
const { isValidOrgDomain } = orgDomainConfig(legacyReq);
const hostname = request.headers.get("host");
if (!hostname) {
return NextResponse.json({ error: "No hostname" }, { status: 400 });
}
const domains = extractSubdomainAndDomain(hostname);
if (!domains) {
return NextResponse.json({ error: "No domains" }, { status: 400 });
}
const [subdomain] = domains;
const teamLogos = await getTeamLogos(subdomain, isValidOrgDomain);
// Resolve all icon types to team logos, falling back to Cal.com defaults.
const type: LogoType = parsedQuery?.type && isValidLogoType(parsedQuery.type) ? parsedQuery.type : "logo";
const logoDefinition = logoDefinitions[type];
const filteredLogo = teamLogos[logoDefinition.source] ?? logoDefinition.fallback;
try {
const response = await fetch(filteredLogo);
const arrayBuffer = await response.arrayBuffer();
let buffer = Buffer.from(arrayBuffer);
// If we need to resize the team logos (via Next.js' built-in image processing)
if (teamLogos[logoDefinition.source] && logoDefinition.w) {
const { detectContentType, optimizeImage } = await import("next/dist/server/image-optimizer");
buffer = await optimizeImage({
buffer,
contentType: detectContentType(buffer) ?? "image/jpeg",
quality: 100,
width: logoDefinition.w,
height: logoDefinition.h, // optional
});
}
// Create a new response with the image buffer
const imageResponse = new NextResponse(buffer);
// Set the appropriate headers
imageResponse.headers.set("Content-Type", response.headers.get("content-type") || "image/png");
imageResponse.headers.set("Cache-Control", "s-maxage=86400, stale-while-revalidate=60");
return imageResponse;
} catch (error) {
return NextResponse.json({ error: "Failed fetching logo" }, { status: 404 });
}
}
export const GET = defaultResponderForAppDir(getHandler);