Merge branch 'hexaaagon/main'

feat: new landing, cleaner code, etc
This commit is contained in:
Conrad Crawford
2024-11-14 01:36:04 -05:00
committed by GitHub
40 changed files with 6337 additions and 3718 deletions

View File

@@ -1,7 +0,0 @@
{
"extends": ["next", "next/core-web-vitals"],
"rules": {
"react/no-unescaped-entities": "off",
"@next/next/no-img-element": "off"
}
}

7
.eslintrc.json Normal file
View File

@@ -0,0 +1,7 @@
{
"extends": ["next", "next/core-web-vitals"],
"rules": {
"react/no-unescaped-entities": "off",
"@next/next/no-img-element": "off"
}
}

13
.gitignore vendored
View File

@@ -1,11 +1,10 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
.env
# dependencies
/node_modules
/.yarn
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
@@ -27,10 +26,12 @@ yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
.env*.local
.env
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -1 +0,0 @@
src/renderCard.tsx

View File

@@ -1,9 +1,10 @@
{
"quoteProps": "consistent",
"printWidth": 120,
"bracketSpacing": true,
"singleQuote": false,
"useTabs": false,
"arrowParens": "avoid",
"tabWidth": 4
"plugins": ["prettier-plugin-tailwindcss"],
"quoteProps": "consistent",
"printWidth": 120,
"bracketSpacing": true,
"singleQuote": false,
"useTabs": false,
"arrowParens": "avoid",
"tabWidth": 2
}

View File

@@ -104,4 +104,4 @@ If you don't want people seeing your discriminator (most likely for privacy reas
\
Note: Current Nitro & Boosting badges **do not work due** to Discord API limitations, unless you currently have an animated avatar, in which case it will display the Nitro badge.
_If you're using this in your profile, feel free to show support and give this repo a ⭐ star! It means a lot, thank you :)_
_If you're using this in your profile, feel free to show support and give this repo a ⭐ star! It means a lot, thank you :)_

20
components.json Normal file
View File

@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/app/globals.css",
"baseColor": "stone",
"cssVariables": false,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}

2
next-env.d.ts vendored
View File

@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.

View File

@@ -1,3 +0,0 @@
module.exports = {
reactStrictMode: true
}

4
next.config.mjs Normal file
View File

@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;

View File

@@ -1,35 +1,41 @@
{
"name": "next-app",
"name": "lanyard-profile-readme",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "next dev --turbopack -p 3001",
"build": "next build",
"start": "next start",
"start": "next start -p 3001",
"lint": "next lint"
},
"packageManager": "pnpm@9.11.0",
"dependencies": {
"@types/escape-html": "^1.0.1",
"@types/ioredis": "^4.28.8",
"@types/styled-components": "^5.1.10",
"axios": "^0.21.1",
"@radix-ui/react-popover": "^1.1.2",
"@types/escape-html": "^1.0.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "1.0.0",
"escape-html": "^1.0.3",
"framer-motion": "^4.1.17",
"image-to-base64": "^2.2.0",
"ioredis": "^4.28.5",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "^5.3.0",
"use-smooth-count": "^0.3.0"
"framer-motion": "12.0.0-alpha.1",
"ioredis": "^5.4.1",
"lucide-react": "^0.453.0",
"next": "15.0.3",
"react": "18.3.1",
"react-dom": "18.3.1",
"swr": "^2.2.5",
"tailwind-merge": "^2.5.4",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/escape-html": "^1.0.1",
"@types/image-to-base64": "^2.1.0",
"@types/react": "^18.2.45",
"eslint": "7.28.0",
"eslint-config-next": "11.0.0",
"prettier": "^2.3.1",
"typescript": "4.3.3"
"@types/node": "^20",
"@types/react": "18.3.12",
"@types/react-dom": "18.3.1",
"eslint": "^8",
"eslint-config-next": "15.0.1",
"postcss": "^8",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

View File

@@ -1,18 +0,0 @@
import type { AppProps } from "next/app";
import Head from "next/head";
export default function LanyardReadMe({ Component, pageProps }: AppProps) {
return (
<>
<Head>
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png" />
<link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#5bbad5" />
<meta name="msapplication-TileColor" content="#191d28" />
<meta name="theme-color" content="#191d28" />
</Head>
<Component {...pageProps} />
</>
);
}

View File

@@ -1,29 +0,0 @@
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(ctx: any) {
const sheet = new ServerStyleSheet(),
originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App: any) => (props: any) => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}

View File

@@ -1,67 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import renderCard from "../../src/renderCard";
import { isSnowflake } from "../../src/snowflake";
import redis from "../../src/redis";
type Data = {
id?: string | string[];
error?: any;
code?: string;
};
type Parameters = {
theme?: string;
bg?: string;
hideStatus?: string;
hideTimestamp?: string;
hideDiscrim?: string;
borderRadius?: string;
animated?: string;
};
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
let getUser: any = {};
if (!req.query.id)
return res.send({
error: `No ID provided.`,
});
const params: Parameters = req.query,
userId = req.query.id[0];
if (!isSnowflake(userId))
return res.send({
error: `That is not a valid snowflake ID!`,
});
try {
getUser.data = await fetch(`https://api.lanyard.rest/v1/users/${userId}`).then(res => res.json());
} catch (error: any) {
if (error.response.data && error.response.data.error.message)
return res
.status(404)
.send({ error: error.response.data.error.message, code: error.response.data.error.code });
if (error.response.status === 404) return res.status(404).send({ error: "Invalid user!" });
console.log(error); // Only console log the error if its not a 404
return res.status(400).send({
error: `Something went wrong! If everything looks correct and this still occurs, please contact @notcnrad on Twitter.`,
});
}
try {
let user = await redis.hget("users", userId);
if (!user) await redis.hset("users", userId, "true");
} catch {
null;
}
res.setHeader("Content-Type", "image/svg+xml; charset=utf-8");
res.setHeader("content-security-policy", "default-src 'none'; img-src * data:; style-src 'unsafe-inline'");
const svg = await renderCard(getUser.data, params);
res.status(200).send(svg as any);
}

View File

@@ -1,9 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import redis from "../../src/redis";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
let users = await redis.hgetall("users");
let count = Object.keys(users);
res.status(200).send({ count: count.length });
}

View File

@@ -1,264 +0,0 @@
import Head from "next/head";
import styled, { createGlobalStyle } from "styled-components";
import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { useSmoothCount } from "use-smooth-count";
export default function Home({ userCount }: { userCount: number }) {
const [userId, setUserId] = useState<null | string>(null);
const [userError, setUserError] = useState<string>();
const [copyState, setCopyState] = useState("Copy");
const countRef = useRef<HTMLDivElement | null>(null);
const counter = useSmoothCount({ ref: countRef, target: userCount, duration: 3, curve: [0, 1, 0, 1] });
const copy = () => {
navigator.clipboard.writeText(
`[![Discord Presence](https://lanyard.cnrad.dev/api/${userId})](https://discord.com/users/${userId})`
);
setCopyState("Copied!");
setTimeout(() => setCopyState("Copy"), 1500);
};
useEffect(() => {
(async () => {
try {
await axios.get(`/api/${userId}`);
setUserError(undefined);
} catch (error: any) {
console.log(error.response);
if (error.response.status === 404 && error.response.data.code == "user_not_monitored")
setUserError(`User not monitored by Lanyard, click to join the discord`);
}
})();
}, [userId]);
return (
<>
<GlobalStyle />
<Head>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400&display=swap"
rel="stylesheet"
/>
<title>Lanyard for GitHub Profile</title>
<meta property="og:title" content="Lanyard for GitHub Profile" key="title" />
<meta
name="description"
content="Utilize Lanyard to display your Discord Presence in your GitHub Profile"
/>
<meta
name="og:description"
content="Utilize Lanyard to display your Discord Presence in your GitHub Profile"
/>
</Head>
<Main>
<Container>
<Title>lanyard profile readme 🏷</Title>
<Paragraph>Utilize Lanyard to display your Discord Presence in your GitHub Profile</Paragraph>
<br />
<Input onChange={el => setUserId(el.target.value)} placeholder="Enter your Discord ID" />
{userId ? (
<>
<Output>
[![Discord Presence](https://lanyard.cnrad.dev/api/{userId}
)](https://discord.com/users/{userId})
</Output>
<ActionButton onClick={copy}>{copyState}</ActionButton>
<a
href="https://github.com/cnrad/lanyard-profile-readme#options"
target="_blank"
rel="noreferrer"
>
<ActionButton>Options</ActionButton>
</a>
<a
style={{ textDecoration: "none" }}
target="_blank"
href={userError && "https://discord.gg/lanyard"}
rel="noreferrer"
>
<Example
src={`/api/${userId}`}
alt={`${userError || "Please provide a valid user ID!"}`}
style={{ color: "#ff8787" }}
/>
</a>
</>
) : null}
</Container>
</Main>
<FooterStat>
Lanyard Profile Readme has <div style={{ fontWeight: "bold", width: "3.2rem" }} ref={countRef} /> total
users!
</FooterStat>
</>
);
}
export async function getServerSideProps(ctx: any) {
let userCount = await axios
.get("https://lanyard.cnrad.dev/api/getUserCount", { timeout: 1000 })
.then(res => res.data.count)
.catch(() => 1000);
return {
props: { userCount },
};
}
const GlobalStyle = createGlobalStyle`
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background: rgb(64 68 78);
border-radius: 8px;
}
::-webkit-scrollbar-track {
background: rgb(24 28 39);
}
`;
const Main = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: start;
margin: 0;
padding: 0;
box-sizing: border-box;
max-width: 100vw;
min-height: 100vh;
background: #010103;
background-size: cover;
`;
const Container = styled.div`
border-radius: 7px;
margin-top: 60px;
width: 80%;
max-width: 450px;
`;
const Title = styled.h1`
text-align: left;
font-size: 2rem;
font-weight: 600;
margin: 5px 0;
color: #cecece;
`;
const Paragraph = styled.p`
color: #aaabaf;
font-size: 1rem;
`;
const Input = styled.input`
text-align: left;
border-radius: 8px;
border: none;
width: 100%;
font-size: 0.9rem;
padding: 0.45rem 0.75rem;
color: #aaabaf;
border: solid 1px rgba(255, 255, 255, 0.2);
background: #000;
box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2);
transition: all ease-in-out 0.1s;
&:focus {
outline: 0;
border-color: rgba(255, 255, 255, 0.5);
}
`;
const Output = styled.div`
margin: 15px 0;
color: #aaabaf;
word-break: break-word;
border-radius: 8px;
border: solid 1px #333;
padding: 8px;
background: #000;
box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2);
font-family: Monospace, sans-serif;
`;
const ActionButton = styled.button`
font-size: 0.9rem;
padding: 5px 25px;
margin-right: 10px;
border-radius: 6px;
cursor: pointer;
color: #888;
border: solid 1px #333;
background: transparent;
transition: all ease-in-out 0.1s;
&:hover {
color: #e6e6e6;
border-color: #e6e6e6;
}
&:active {
color: #fff;
border-color: #fff;
}
`;
const Example = styled.img`
display: block;
margin: 30px auto 0px;
max-width: 100%;
`;
const FooterStat = styled.div`
position: absolute;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
line-height: 1rem;
bottom: 1rem;
left: 50%;
transform: translate(-50%, 0);
background: #000;
padding: 1rem 1.25rem;
color: #fff;
border-radius: 0.55rem;
text-align: center;
box-shadow: 0 2px 15px -10px #a21caf;
min-width: 400px;
@media (max-width: 400px) {
font-size: 14px;
min-width: 365px;
padding: 0.75rem 1rem;
}
&:before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 0.55rem;
border: 2px solid transparent;
background: linear-gradient(45deg, #be123c, #6b21a8, #3730a3) border-box;
-webkit-mask: linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
`;

4739
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

8
postcss.config.mjs Normal file
View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

View File

@@ -1,4 +0,0 @@
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,79 @@
import redis from "@/utils/redis";
import renderCard, { Parameters } from "@/utils/renderCard";
import { isSnowflake } from "@/utils/snowflake";
import { NextRequest } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(req: NextRequest, options: { params: Promise<{ id: string[] }> }) {
const userId = (await options.params).id.join("/");
if (!userId)
return Response.json(
{
data: {
error: "No ID provided.",
},
success: false,
},
{
status: 400,
},
);
if (!isSnowflake(userId))
return Response.json(
{
data: {
error: "The ID you provide is not a valid snowflake.",
},
success: false,
},
{
status: 400,
},
);
let getUser: any = {};
getUser.data = await fetch(`https://api.lanyard.rest/v1/users/${userId}`, {
cache: "no-store",
}).then(async res => {
const data = await res.json();
if (!data.success) {
getUser.error = data.error;
}
return data;
});
if (getUser.error) {
return Response.json(
{
data: getUser.error,
success: false,
},
{
status: 400,
},
);
}
const params: Parameters = Object.fromEntries(req.nextUrl.searchParams.entries());
try {
let user = await redis.hget("users", userId);
if (!user) await redis.hset("users", userId, "true");
} catch {
null;
}
return new Response(await renderCard(getUser.data, params), {
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"content-security-policy": "default-src 'none'; img-src * data:; style-src 'unsafe-inline'",
},
status: 200,
});
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

42
src/app/globals.css Normal file
View File

@@ -0,0 +1,42 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #010103;
--foreground: #171717;
}
body {
color: var(--foreground);
background: var(--background);
font-family: "Poppins", sans-serif;
}
@layer base {
:root {
--radius: 0.5rem;
}
}
/* width */
::-webkit-scrollbar {
width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
background: #131313;
border-radius: 6px;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: #525252;
border-radius: 6px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: #303030;
}

34
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import "./globals.css";
import { Poppins } from "next/font/google";
const poppins = Poppins({
weight: ["400", "500", "600", "700"],
subsets: ["latin"],
display: "swap",
});
export const metadata: Metadata = {
title: "Lanyard for GitHub Profile",
description: "Display your Discord Presence anywhere, using Lanyard",
openGraph: {
title: "Lanyard for GitHub Profile",
description: "Display your Discord Presence anywhere, using Lanyard",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
{/* Supress Hydration Warning that caused by some extensions such as Colorzilla, do not remove this. */}
<body className={`${poppins.className} antialiased`} suppressHydrationWarning>
{children}
</body>
</html>
);
}

365
src/app/page.tsx Normal file
View File

@@ -0,0 +1,365 @@
"use client";
import React, { useState, JSX, useRef, useEffect } from "react";
import { motion } from "framer-motion";
import useSWR from "swr";
import { getUserCount } from "@/utils/actions";
import { isSnowflake } from "@/utils/snowflake";
import Link from "next/link";
import { PARAMETER_INFO } from "@/utils/parameters";
import * as Icon from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/popover";
import { cn, filterLetters } from "@/lib/utils";
export default function Home() {
const ORIGIN_URL = process.env.NODE_ENV === "development" ? "http://localhost:3000" : "https://lanyard.cnrad.dev";
const [userId, setUserId] = useState("");
const [userError, setUserError] = useState<string | JSX.Element>();
const [copyState, setCopyState] = useState("Copy");
const [outputType, setOutputType] = useState<"markdown" | "html" | "url">("markdown");
const [isLoaded, setIsLoaded] = useState(false);
const [options, setOptions] = useState<Record<string, string | boolean>>({});
const userCount = useSWR("getUserCount", getUserCount);
async function onLoadDiscordId(userId: string) {
setUserId(userId);
setIsLoaded(false);
setUserError(undefined);
if (userId.length < 1) return;
if (userId.length > 0 && !isSnowflake(userId)) return setUserError("Invalid Discord ID");
}
const url = `${ORIGIN_URL}/api/${userId}${
Object.keys(options).length > 0
? `?${Object.keys(options)
.map(option => `${option}=${options[option]}`)
.join("&")}`
: ""
}`;
const copyContent = {
markdown: `[![Discord Presence](${url})](https://discord.com/users/${userId})`,
html: `<a href="https://discord.com/users/${userId}"><img src="${url}" /></a>`,
url: `${url}`,
};
const [isOptionsOpen, setIsOptionsOpen] = useState(false);
const optionsTriggerRef = useRef<HTMLButtonElement | null>(null);
const optionsContentRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
function handleOptionsClickOutside(event: MouseEvent) {
if (
isOptionsOpen &&
optionsContentRef.current &&
!optionsContentRef.current.contains(event.target as Node) &&
!optionsTriggerRef.current?.contains(event.target as Node)
) {
setIsOptionsOpen(false);
}
}
document.addEventListener("mousedown", handleOptionsClickOutside);
return () => {
document.removeEventListener("mousedown", handleOptionsClickOutside);
};
}, [isOptionsOpen]);
return (
<>
<main className="flex min-h-screen max-w-[100vw] flex-col items-center">
<div className="relative mt-16 flex w-[80%] max-w-[28rem] flex-col gap-2 rounded-md">
<p className="text-left text-3xl font-semibold text-[#cecece]">🏷 lanyard-profile-readme </p>
<p className="mb-2 text-sm text-[#aaabaf]">
Uses{" "}
<a
href="https://github.com/Phineas/lanyard"
target="_blank"
rel="noreferrer noopener"
className="text-white underline decoration-transparent underline-offset-2 transition-colors duration-150 ease-out hover:decoration-white"
>
Lanyard
</a>{" "}
to display your Discord Presence anywhere.
</p>
<div className="flex h-[2.25rem] w-full flex-row gap-2">
<input
className="w-full rounded-lg border border-white/10 bg-transparent px-2.5 py-1.5 font-mono text-sm text-gray-200 transition-colors duration-150 ease-out focus:border-white/50 focus:outline-none"
onChange={e => onLoadDiscordId(e.target.value)}
value={userId || ""}
placeholder="Enter your Discord ID"
/>
<button
ref={optionsTriggerRef}
onClick={() => setIsOptionsOpen(p => !p)}
className="group flex min-h-[2.25rem] min-w-[2.25rem] items-center justify-center rounded-lg border border-white/10 bg-stone-900/50 transition-colors duration-150 ease-out hover:border-white/40"
>
<Icon.Settings size={18} className="text-white/40 group-hover:text-white/60" />
</button>
</div>
<motion.div
initial={{
scale: 0.98,
opacity: isOptionsOpen ? 1 : 0,
display: isOptionsOpen ? "block" : "none",
}}
animate={{
scale: isOptionsOpen ? 1 : 0.98,
opacity: isOptionsOpen ? 1 : 0,
display: isOptionsOpen ? "block" : "none",
}}
ref={optionsContentRef}
transition={{ duration: 0.2, ease: [0, 0.6, 0.4, 1] }}
className={cn(
"absolute top-32 z-[2] flex h-auto flex-col overflow-hidden rounded-lg border border-white/5 bg-black/75 p-4 text-white shadow-[0_6px_50px_-25px_rgba(180,177,255,0.2)] backdrop-blur-xl max-sm:h-[30rem] max-sm:w-full max-sm:overflow-y-scroll sm:-left-[1rem] sm:w-[30rem] sm:max-w-[30rem]",
)}
>
<div className="grid-rows-auto mb-4 flex w-full flex-col gap-2.5 sm:grid sm:grid-cols-2">
{PARAMETER_INFO.filter(item => item.type !== "boolean").map(item => {
return (
<div key={item.parameter} className="flex flex-col gap-1.5">
<div className="flex items-center gap-2">
<p className="text-sm text-gray-300">{item.title}</p>
<Popover>
<PopoverTrigger>
<Icon.InfoIcon
size={16}
className="rounded-md text-zinc-700 transition hover:text-gray-400"
/>
</PopoverTrigger>
<PopoverContent side="top" className="text-sm">
{item.description}
</PopoverContent>
</Popover>
</div>
{item.type === "string" && (
<input
className="relative h-8 w-full appearance-none rounded-md border border-white/10 bg-transparent px-2 py-0.5 text-sm outline-none transition-all duration-150 ease-out placeholder:text-white/30 focus:border-white/50 disabled:cursor-not-allowed disabled:opacity-50"
placeholder={item.options?.placeholder || "..."}
onChange={e => {
const filteredValue = encodeURIComponent(
filterLetters(
e.target.value,
(PARAMETER_INFO.find(p => p.parameter === item.parameter) as any).options.omit,
),
);
setOptions(prev => ({
...prev,
[item.parameter]: filteredValue,
}));
}}
value={decodeURIComponent((options[item.parameter] as string) || "")}
/>
)}
{item.type === "list" && (
<div className="relative">
<select
value={(options[item.parameter] as string) || ""}
onChange={e =>
setOptions(prev => ({
...prev,
[item.parameter]: e.target.value,
}))
}
className={cn(
"relative h-8 w-full appearance-none rounded-md border border-white/10 bg-transparent px-2 py-0.5 text-sm outline-none transition-all duration-150 ease-out placeholder:text-white/30 focus:border-white/50 disabled:cursor-not-allowed disabled:opacity-50",
{
"text-white/30": !options[item.parameter] || options[item.parameter] === "",
},
)}
>
<option value="" className="bg-background">
None
</option>
{item.options.list.map(option => (
<option value={option.value} key={option.value} className="bg-background">
{option.name}
</option>
))}
</select>
<Icon.ChevronDown
size={14}
className="absolute right-2 top-0 my-auto flex h-full text-white/50"
/>
</div>
)}
</div>
);
})}
</div>
{/* Separated for easier styling/readability */}
<div className="sm:grid-rows-auto flex flex-col gap-2 sm:grid sm:grid-cols-2">
{PARAMETER_INFO.filter(item => item.type === "boolean").map(item => {
return (
<div key={item.parameter} className="flex flex-row items-start gap-2.5 text-sm">
<input
type="checkbox"
className={cn(
"mt-0.5 max-h-4 min-h-4 min-w-4 max-w-4 cursor-pointer appearance-none before:overflow-clip before:rounded-[0.25rem] after:absolute after:h-4 after:w-4 after:rounded-[0.25rem] after:border after:border-white/10 after:transition-all after:duration-150 after:ease-out",
{
"after:border-gray-200/50 after:bg-gray-500/40": options[item.parameter] === "true",
"after:bg-zinc-700/10 after:hover:bg-zinc-700/25": options[item.parameter] !== "true",
},
)}
checked={options[item.parameter] === "true"}
onChange={e =>
setOptions(prev => ({
...prev,
[item.parameter]: e.target.checked.toString(),
}))
}
/>
<p
className="text-gray-300"
style={{
textDecoration: PARAMETER_INFO.find(p => p.parameter === item.parameter)?.deprecated
? "line-through"
: "none",
}}
>
{item.title}
</p>
<Popover>
<PopoverTrigger>
<Icon.InfoIcon
size={16}
className="mt-0.5 rounded-md text-zinc-700 transition hover:text-gray-400"
/>
</PopoverTrigger>
<PopoverContent side="top" className="text-sm">
{item.description}
</PopoverContent>
</Popover>
</div>
);
})}
</div>
</motion.div>
{!isLoaded ? (
<motion.p
variants={{
open: { opacity: 1, display: "block" },
closed: { opacity: 0, display: "none" },
}}
initial="closed"
animate={userError ? "open" : "closed"}
className="mt-1 text-sm text-red-500"
transition={{ duration: 0.15 }}
>
{userError}
</motion.p>
) : null}
<motion.div
variants={{
loaded: {
opacity: 1,
},
waiting: {
opacity: 0,
},
}}
initial="waiting"
animate={isLoaded ? "loaded" : "waiting"}
transition={{ duration: 0.15 }}
className="mt-2 flex flex-col gap-2"
>
<img
src={url}
height={280}
width={500}
alt="Your Lanyard Banner"
onLoad={() => setIsLoaded(true)}
onError={() =>
userId.length > 0 && isSnowflake(userId)
? setUserError(
<>
User is not monitored by Lanyard, please join{" "}
<Link href="https://discord.gg/lanyard" target="_blank" className="inline underline">
the server
</Link>{" "}
and try again.
</>,
)
: null
}
/>
<div className="mt-4 grid grid-cols-3 gap-1">
{(["markdown", "html", "url"] as const).map(type => (
<button
key={type}
className={cn(
"rounded-md border border-white/10 px-1.5 py-1 font-mono text-sm font-medium uppercase tracking-wide text-white/50 transition-colors duration-100 ease-out",
{
"border-white/20 bg-white/10 font-semibold text-white/75": outputType === type,
"hover:border-white/15 hover:bg-white/5": outputType !== type,
},
)}
onClick={() => setOutputType(type)}
>
{type}
</button>
))}
</div>
<div className="break-all rounded-lg border border-white/10 bg-zinc-950 px-3 py-2 font-mono text-sm text-blue-400">
{copyContent[outputType]}
</div>
<div className="flex gap-2">
<button
className="rounded-md border border-white/10 px-3 py-1 font-mono text-sm font-medium text-white/50 transition-colors duration-75 ease-out hover:border-white/20 hover:text-white/75"
onClick={() => {
navigator.clipboard.writeText(copyContent[outputType]);
setCopyState("Copied!");
setTimeout(() => setCopyState("Copy"), 1500);
}}
>
{copyState}
</button>
</div>
</motion.div>
</div>
</main>
{userCount.data && (
<motion.div
initial={{
scale: 0.99,
opacity: 0,
transform: "translateY(10px) translateX(-50%)",
}}
animate={{
scale: 1,
opacity: 1,
transform: "translateY(0) translateX(-50%)",
}}
transition={{ duration: 1.25, ease: [0, 0.4, 0.2, 1] }}
className={cn(
"fixed bottom-0 left-1/2 mb-8 flex h-min w-min min-w-[10rem] flex-row items-center justify-center whitespace-nowrap rounded-full border border-white/5 bg-[#2A2A2A]/15 px-4 py-2.5 text-center text-sm leading-[1rem] text-white/50 shadow-[0_4px_45px_-20px_#b390ff] max-sm:hidden",
)}
>
Currently at&nbsp;
<span className="bg-gradient-to-tr from-red-500 to-purple-700 bg-clip-text font-semibold text-transparent drop-shadow-[0_0_8px_#a931ff]">
{userCount.data?.toLocaleString()}
</span>
&nbsp;total users!
</motion.div>
)}
</>
);
}

View File

@@ -0,0 +1,29 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border border-white/10 bg-black/50 p-4 text-stone-50 shadow-md outline-none backdrop-blur-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@@ -1,19 +0,0 @@
export const getFlags = (flag: number): string[] => {
let flags: string[] = [];
// In the order they appear on profiles
if (flag & 1) flags.push("Discord_Employee"); // 1 << 0
if (flag & 262144) flags.push("Discord_Certified_Moderator"); // 1 << 18
if (flag & 2) flags.push("Partnered_Server_Owner"); // 1 << 1
if (flag & 4) flags.push("HypeSquad_Events"); // 1 << 2
if (flag & 64) flags.push("House_Bravery"); // 1 << 6
if (flag & 128) flags.push("House_Brilliance"); // 1 << 7
if (flag & 256) flags.push("House_Balance"); // 1 << 8
if (flag & 8) flags.push("Bug_Hunter_Level_1"); // 1 << 3
if (flag & 16384) flags.push("Bug_Hunter_Level_2"); // 1 << 14
if (flag & 4194304) flags.push("Active_Developer"); // 1 << 22
if (flag & 131072) flags.push("Early_Verified_Bot_Developer"); // 1 << 17
if (flag & 512) flags.push("Early_Supporter"); // 1 << 9
return flags;
};

13
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,13 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function filterLetters(str: string, lettersToRemove: string[] = []) {
lettersToRemove.forEach((letter) => {
str = str.replaceAll(letter, "");
});
return str;
}

View File

@@ -1,578 +0,0 @@
// probably the messiest code i've ever written but it works so :)
import { Badges } from "../public/assets/badges/BadgesEncoded";
import { getFlags } from "./getFlags";
import * as LanyardTypes from "./LanyardTypes";
import { encodeBase64 } from "./toBase64";
import escape from "escape-html";
type Parameters = {
theme?: string;
bg?: string;
clanbg?: string;
animated?: string;
animatedDecoration?: string;
hideDiscrim?: string;
hideStatus?: string;
hideTimestamp?: string;
hideBadges?: string;
hideProfile?: string;
hideActivity?: string;
hideSpotify?: string;
hideClan?: string;
hideDecoration?: string;
ignoreAppId?: string;
showDisplayName?: string;
borderRadius?: string;
idleMessage?: string;
};
const parseBool = (string: string | undefined): boolean => string === "true" ? true : false;
const parseAppId = (string: string | undefined): Array<string> => {
if (string === undefined) return [];
return string.split(",");
}
const elapsedTime = (timestamp: any) => {
let startTime = timestamp;
let endTime = Number(new Date());
let difference = (endTime - startTime) / 1000;
// we only calculate them, but we don't display them.
// this fixes a bug in the Discord API that does not send the correct timestamp to presence.
let daysDifference = Math.floor(difference / 60 / 60 / 24);
difference -= daysDifference * 60 * 60 * 24;
let hoursDifference = Math.floor(difference / 60 / 60);
difference -= hoursDifference * 60 * 60;
let minutesDifference = Math.floor(difference / 60);
difference -= minutesDifference * 60;
let secondsDifference = Math.floor(difference);
return `${hoursDifference >= 1 ? ("0" + hoursDifference).slice(-2) + ":" : ""}${("0" + minutesDifference).slice(
-2
)}:${("0" + secondsDifference).slice(-2)}`;
};
const renderCard = async (body: LanyardTypes.Root, params: Parameters): Promise<string> => {
let { data } = body;
let avatarBorderColor: string = "#747F8D",
avatarExtension: string = "webp",
statusExtension: string = "webp",
activity: any = false,
backgroundColor: string = "1a1c1f",
theme = "dark",
borderRadius = "10px",
idleMessage = "I'm not currently doing anything!";
let hideStatus = parseBool(params.hideStatus);
let hideTimestamp = parseBool(params.hideTimestamp);
let hideBadges = parseBool(params.hideBadges);
let hideProfile = parseBool(params.hideProfile);
let hideActivity = params.hideActivity ?? "false";
let hideSpotify = parseBool(params.hideSpotify);
let hideClan = parseBool(params.hideClan);
let hideDecoration = parseBool(params.hideDecoration);
let ignoreAppId = parseAppId(params.ignoreAppId);
let hideDiscrim = parseBool(params.hideDiscrim);
let showDisplayName = parseBool(params.showDisplayName);
if (!data.discord_user.avatar_decoration_data) hideDecoration = true;
if (parseBool(params.hideDiscrim) || body.data.discord_user.discriminator === "0") hideDiscrim = true;
if (!body.data.discord_user.clan) hideClan = true;
if (data.activities[0]?.emoji?.animated) statusExtension = "gif";
if (data.discord_user.avatar && data.discord_user.avatar.startsWith("a_")) avatarExtension = "gif";
if (params.animated === "false") avatarExtension = "webp";
if (params.theme === "light") {
backgroundColor = "#eee";
theme = "light";
}
if (params.bg) backgroundColor = params.bg;
let clanBackgroundColor: string = theme === "light" ? "#e0dede" : "#111214";
if (params.clanbg) clanBackgroundColor = params.clanbg;
if (params.idleMessage) idleMessage = params.idleMessage;
if (params.borderRadius) borderRadius = params.borderRadius;
let avatar: string;
if (data.discord_user.avatar) {
avatar = await encodeBase64(
`https://cdn.discordapp.com/avatars/${data.discord_user.id}/${
data.discord_user.avatar
}.${avatarExtension}?size=${avatarExtension === "gif" ? "64" : "256"}`
);
} else {
avatar = await encodeBase64(
`https://cdn.discordapp.com/embed/avatars/${data.discord_user.discriminator === "0"
? ((Number(BigInt(data.discord_user.id) >> BigInt(22))) % 6)
: Number(data.discord_user.discriminator) % 5}.png`
);
}
let clanBadge: string;
if (data.discord_user.clan) {
clanBadge = await encodeBase64(
`https://cdn.discordapp.com/clan-badges/${data.discord_user.clan.identity_guild_id}/${data.discord_user.clan.badge}.png?size=16`
);
}
let avatarDecoration: string;
if (data.discord_user.avatar_decoration_data) {
avatarDecoration = await encodeBase64(
`https://cdn.discordapp.com/avatar-decoration-presets/${data.discord_user.avatar_decoration_data.asset}.png?size=64&passthrough=${params.animatedDecoration || "true"}`
);
}
switch (data.discord_status) {
case "online":
avatarBorderColor = "#43B581";
break;
case "idle":
avatarBorderColor = "#FAA61A";
break;
case "dnd":
avatarBorderColor = "#F04747";
break;
case "offline":
avatarBorderColor = "#747F8D";
break;
}
let flags: string[] = getFlags(data.discord_user.public_flags);
if (data.discord_user.avatar && data.discord_user.avatar.includes("a_")) flags.push("Nitro");
let userStatus: Record<string, any> | null = null;
if (data.activities[0] && data.activities[0].type === 4) userStatus = data.activities[0];
const activities = data.activities
// Filter only type 0
.filter(activity => activity.type === 0)
// Filter ignored app ID
.filter(activity => !ignoreAppId.includes(activity.application_id ?? ""));
// Take the highest one
activity = Array.isArray(activities) ? activities[0] : activities;
// Calculate height of parent SVG element
const svgHeight = (): string => {
if (hideProfile) return "130";
if (hideActivity === "true") return "91";
if (hideActivity === "whenNotUsed" && !activity && !data.listening_to_spotify) return "91";
if (hideSpotify && data.listening_to_spotify) return "210";
return "210";
}
// Calculate height of main div element
const divHeight = (): string => {
if (hideProfile) return "120";
if (hideActivity === "true") return "81";
if (hideActivity === "whenNotUsed" && !activity && !data.listening_to_spotify) return "81";
if (hideSpotify && data.listening_to_spotify) return "200";
return "200";
}
return `
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xhtml="http://www.w3.org/1999/xhtml" width="410px" height="${svgHeight()}px">
<defs>
<style>
.hover-opacity:hover {
opacity: 0.25;
}
.transition {
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 200ms;
}
</style>
</defs>
<foreignObject x="0" y="0" width="410" height="${svgHeight()}">
<div xmlns="http://www.w3.org/1999/xhtml" style="
position: absolute;
width: 400px;
height: ${divHeight()}px;
inset: 0;
background-color: #${backgroundColor};
color: ${theme === "dark" ? "#fff" : "#000"};
font-family: 'Century Gothic', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
font-size: 16px;
display: flex;
flex-direction: column;
padding: 5px;
border-radius: ${borderRadius};
">
${
hideProfile ? "" : `
<div style="
width: 400px;
height: 100px;
inset: 0;
display: flex;
flex-direction: row;
padding-bottom: 5px;
${hideActivity !== "false" && !activity && !data.listening_to_spotify ?
""
: `border-bottom: solid 0.5px ${theme === "dark" ?
"hsl(0, 0%, 100%, 10%)"
: "hsl(0, 0%, 0%, 10%)"
}`
}
">
<div style="
display: flex;
position: relative;
flex-direction: row;
height: 80px;
width: 80px;
">
<img src="data:image/png;base64,${avatar}"
style="
border-radius: 50%;
width: 50px;
height: 50px;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
"/>
${hideDecoration || !data.discord_user.avatar_decoration_data ? "" : `
<img src="data:image/png;base64,${avatarDecoration!}"
class="hover-opacity transition"
style="
display: block;
width: 64px;
height: 64px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
"/>
`}
<span style="
position: absolute;
bottom: 14px;
right: 14px;
height: 13px;
width: 13px;
background-color: ${avatarBorderColor};
border-radius: 50%;
border: 3px solid #${backgroundColor};
" />
</div>
<div style="
height: 80px;
width: 260px;
display: flex;
flex-direction: column;
justify-content: center;
">
<div style="
display: flex;
flex-direction: row;
height: 25px;
">
<h1 style="
font-size: 1.15rem;
margin: 0 12px 0 0;
white-space: nowrap;
">
${escape(showDisplayName ? data.discord_user.global_name : data.discord_user.username)}${
!hideDiscrim && !showDisplayName
? `<span style="color: ${theme === "dark" ? "#ccc" : "#666"}; font-weight: lighter;">#${
data.discord_user.discriminator
}</span>`
: ""
}
</h1>
${hideClan || !data.discord_user.clan?.tag && !data.discord_user.clan?.badge ? "" : `
<span style="
background-color: ${clanBackgroundColor};
border-radius: 0.375rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
margin-left: -6px;
margin-right: 12px;
display: flex;
align-items: center;
gap: 0.25rem;
font-size: 16px;
font-weight: 500;
height: 100%;
">
<img src="data:image/png;base64,${clanBadge!}" />
<p style="margin-bottom: 1.1rem">${escape(data.discord_user.clan!.tag)}</p>
</span>
`}
${hideBadges ? "" : flags.map(v => `
<img src="data:image/png;base64,${Badges[v]}" style="
width: auto;
height: 20px;
position: relative;
top: 50%;
transform: translate(0%, -50%);
margin-right: 7px;
" />`).join("")
}
</div>
${showDisplayName ?
`<h2 style="
font-size: 0.95rem;
margin: 0;
white-space: nowrap;
font-weight: 400;
">
${escape(data.discord_user.username)}
</h2>`
: ``
}
${
userStatus && !hideStatus ? `
<p style="
font-size: 0.9rem;
margin: 0;
color: ${theme === "dark" ? "#aaa" : "#333"};
font-weight: 400;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
">
${
userStatus.emoji?.id ? `
<img src="data:image/png;base64,${await encodeBase64(
`https://cdn.discordapp.com/emojis/${userStatus.emoji.id}.${statusExtension}`
)}"
style="
width: 15px;
height: 15px;
position: relative;
top: 10px;
transform: translate(0%, -50%);
margin: 0 2px 0 0;
" />` : ''
}
${
userStatus.state && userStatus.emoji?.name && !userStatus.emoji.id
? `${userStatus.emoji.name} ${escape(userStatus.state)}`
: userStatus.state
? escape(userStatus.state)
: !userStatus.state && userStatus.emoji?.name && !userStatus.emoji.id
? escape(userStatus.emoji.name)
: ''
}
</p>` : ``
}
</div>
</div>`
}
${
activity ? `
<div style="
display: flex;
flex-direction: row;
height: 120px;
margin-left: 15px;
font-size: 0.75rem;
padding-top: 18px;
">
<div style="
margin-right: 15px;
width: auto;
height: auto;
">
${
activity.assets?.large_image ? `
<img src="data:image/png;base64,${await encodeBase64(
activity.assets.large_image.startsWith("mp:external/")
? `https://media.discordapp.net/external/${activity.assets.large_image.replace("mp:external/", "")}`
: `https://cdn.discordapp.com/app-assets/${activity.application_id}/${activity.assets.large_image}.webp`
)}"
style="
width: 80px;
height: 80px;
border: solid 0.5px #222;
border-radius: 10px;
"/>
` : `
<img src="data:image/png;base64,${await encodeBase64(
`https://lanyard-profile-readme.vercel.app/assets/unknown.png`
)}" style="
width: 70px;
height: 70px;
margin-top: 4px;
filter: invert(100);
"/>
`}
${
activity.assets?.small_image ? `
<img src="data:image/png;base64,${await encodeBase64(
activity.assets.small_image.startsWith("mp:external/")
? `https://media.discordapp.net/external/${activity.assets.small_image.replace("mp:external/", "")}`
: `https://cdn.discordapp.com/app-assets/${activity.application_id}/${activity.assets.small_image}.webp`
)}"
style="
width: 30px;
height: 30px;
border-radius: 50%;
margin-left: -26px;
margin-bottom: -8px;
"/>` : ``
}
</div>
<div style="
color: #999;
margin-top: ${
activity.timestamps?.start && !hideTimestamp
? "-6px"
: "5px"
};
line-height: 1;
width: 279px;
">
<p style="
color: ${theme === "dark" ? "#fff" : "#000"};
font-size: 0.85rem;
font-weight: bold;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
height: 15px;
margin: 7px 0;
">${escape(activity.name)}</p>
${
activity.details
? `
<p style="
color: ${theme === "dark" ? "#ccc" : "#777"};
overflow: hidden;
white-space: nowrap;
font-size: 0.85rem;
text-overflow: ellipsis;
height: 15px;
margin: 7px 0;
">${escape(activity.details)}</p>`
: ``
}
${
activity.state
? `
<p style="
color: ${theme === "dark" ? "#ccc" : "#777"};
overflow: hidden;
white-space: nowrap;
font-size: 0.85rem;
text-overflow: ellipsis;
height: 15px;
margin: 7px 0;
">${escape(activity.state)}${
activity.party?.size
? ` (${activity.party.size[0]} of ${activity.party.size[1]})`
: ""
}</p>` : ``
}
${
activity.timestamps?.start && !hideTimestamp ? `
<p style="
color: ${theme === "dark" ? "#ccc" : "#777"};
overflow: hidden;
white-space: nowrap;
font-size: 0.85rem;
text-overflow: ellipsis;
height: 15px;
margin: 7px 0;
">${elapsedTime(new Date(activity.timestamps.start).getTime())} elapsed</p>`
: ``
}
</div>
</div>
` : ``
}
${
data.listening_to_spotify && !activity && !hideSpotify && data.activities[Object.keys(data.activities).length - 1].type === 2
? `
<div style="
display: flex;
flex-direction: row;
height: 120px;
margin-left: 15px;
font-size: 0.8rem;
padding-top: 18px;
">
<img src="${await (async () => {
const album = await encodeBase64(data.spotify.album_art_url);
if (album) return `data:image/png;base64,${album}" style="border: solid 0.5px #222;`;
return 'https://lanyard-profile-readme.vercel.app/assets/unknown.png" style="filter: invert(100);';
})()}
width: 80px;
height: 80px;
border-radius: 10px;
margin-right: 15px;
"/>
<div style="
color: #999;
margin-top: -3px;
line-height: 1;
width: 279px;
">
<p style="font-size: 0.75rem; font-weight: bold; color: ${
theme === "dark" ? "#1CB853" : "#0d943d"
}; margin-bottom: 15px;">LISTENING TO SPOTIFY...</p>
<p style="
height: 15px;
color: ${theme === "dark" ? "#fff" : "#000"};
font-weight: bold;
font-size: 0.85rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin: 7px 0;
">${escape(data.spotify.song)}</p>
<p style="
margin: 7px 0;
height: 15px;
overflow: hidden;
white-space: nowrap;
font-size: 0.85rem;
text-overflow: ellipsis;
color: ${theme === "dark" ? "#ccc" : "#777"};
">By ${escape(data.spotify.artist)}</p>
</div>
</div>
` : ``
}
${
!activity && (!data.listening_to_spotify || hideSpotify) && hideActivity === "false"
? `<div style="
display: flex;
flex-direction: row;
height: 150px;
justify-content: center;
align-items: center;
">
<p style="
font-style: italic;
font-size: 0.8rem;
color: ${theme === "dark" ? "#aaa" : "#444"};
height: auto;
text-align: center;
">
${escape(idleMessage)}
</p>
</div>` : ``
}
</div>
</foreignObject>
</svg>
`;
};
export default renderCard;

View File

@@ -1,13 +0,0 @@
import imageToBase64 from "image-to-base64";
export const encodeBase64 = async (url: string): Promise<string> => {
let response = "";
try {
response = await imageToBase64(url);
} catch (e) {
console.log(e);
}
return response;
};

9
src/utils/actions.ts Normal file
View File

@@ -0,0 +1,9 @@
"use server";
import redis from "@/utils/redis";
export async function getUserCount() {
let users = await redis.hgetall("users");
let count = Object.keys(users);
return count.length;
}

26
src/utils/helpers.ts Normal file
View File

@@ -0,0 +1,26 @@
import type { renderToStaticMarkup as _renderToStaticMarkup } from "react-dom/server";
export let renderToStaticMarkup: typeof _renderToStaticMarkup;
import("react-dom/server").then(module => {
renderToStaticMarkup = module.renderToStaticMarkup;
});
export const getFlags = (flag: number): string[] => {
let flags: string[] = [];
// In the order they appear on profiles
if (flag & 1) flags.push("Discord_Employee"); // 1 << 0
if (flag & 262144) flags.push("Discord_Certified_Moderator"); // 1 << 18
if (flag & 2) flags.push("Partnered_Server_Owner"); // 1 << 1
if (flag & 4) flags.push("HypeSquad_Events"); // 1 << 2
if (flag & 64) flags.push("House_Bravery"); // 1 << 6
if (flag & 128) flags.push("House_Brilliance"); // 1 << 7
if (flag & 256) flags.push("House_Balance"); // 1 << 8
if (flag & 8) flags.push("Bug_Hunter_Level_1"); // 1 << 3
if (flag & 16384) flags.push("Bug_Hunter_Level_2"); // 1 << 14
if (flag & 4194304) flags.push("Active_Developer"); // 1 << 22
if (flag & 131072) flags.push("Early_Verified_Bot_Developer"); // 1 << 17
if (flag & 512) flags.push("Early_Supporter"); // 1 << 9
return flags;
};

193
src/utils/parameters.ts Normal file
View File

@@ -0,0 +1,193 @@
export type Parameters = {
theme?: string;
bg?: string;
clanbg?: string;
animated?: string;
animatedDecoration?: string;
hideDiscrim?: string;
hideStatus?: string;
hideTimestamp?: string;
hideBadges?: string;
hideProfile?: string;
hideActivity?: string;
hideSpotify?: string;
hideClan?: string;
hideDecoration?: string;
ignoreAppId?: string;
showDisplayName?: string;
borderRadius?: string;
idleMessage?: string;
};
export type IParameterInfo = Array<
{ deprecated?: boolean } & (
| {
parameter: string;
type: "boolean";
title: string;
description?: string;
options?: {
defaultBool?: boolean;
};
}
| {
parameter: string;
type: "string";
title: string;
description?: string;
options?: {
placeholder?: string;
omit?: string[];
};
}
| {
parameter: string;
type: "list";
title: string;
description?: string;
options: {
list: Array<{
name: string;
value: string;
}>;
};
}
)
>;
export const PARAMETER_INFO: IParameterInfo = [
{
parameter: "theme",
type: "list",
title: "Theme",
description: "Changes the background and text colors. Can be overridden with the `bg` parameter.",
options: {
list: [
{
name: "Light",
value: "light",
},
{
name: "Dark",
value: "dark",
},
],
},
},
{
parameter: "bg",
type: "string",
title: "Background Color",
description: "Changes the background color to a hex color (no octothorpe).",
options: {
placeholder: "1A1C1F",
omit: ["#"],
},
},
{
parameter: "borderRadius",
type: "string",
title: "Border Radius",
description: "Changes the border radius of the card. Follows the CSS <length> spec (px, rem, etc.).",
options: {
placeholder: "10px",
},
},
{
parameter: "animated",
type: "boolean",
title: "Disable Animated Avatar",
description: "Disables an animated avatar.",
options: {
defaultBool: true,
},
},
{
parameter: "idleMessage",
type: "string",
title: "Idle Message",
description: 'Changes the idle message. Defaults to "I\'m not currently doing anything!".',
options: {
placeholder: "I'm not currently doing anything!",
},
},
{
parameter: "showDisplayName",
type: "boolean",
title: "Show Display Name",
description: "Shows your global display name alongside your username.",
},
{
parameter: "animatedDecoration",
type: "boolean",
title: "Disable Animated Avatar Decoration",
description: "Disables animated avatar decorations.",
options: {
defaultBool: true,
},
},
{
parameter: "hideDecoration",
type: "boolean",
title: "Hide Avatar Decoration",
description: "Hides any avatar decorations.",
},
{
parameter: "hideStatus",
type: "boolean",
title: "Hide Status",
description: "Hides your custom Discord status.",
},
{
parameter: "hideTimestamp",
type: "boolean",
title: "Hide Activity Time",
description: "Hides the time spent on an activity.",
},
{
parameter: "hideClan",
type: "boolean",
title: "Hide Clan Tag",
description: "Hides your Guild Tag (formerly Clan Tag)",
},
{
parameter: "hideBadges",
type: "boolean",
title: "Hide Badges",
description: "Hides your profile badges.",
},
{
parameter: "hideProfile",
type: "boolean",
title: "Hide Profile",
description: "Hides your profile, keeps your activity.",
},
{
parameter: "hideActivity",
type: "boolean",
title: "Hide Activity",
description: "Hides your activity, keeps your profile.",
},
{
parameter: "hideSpotify",
type: "boolean",
title: "Hide Spotify",
description: "Hides your Spotify activity only.",
},
{
parameter: "ignoreAppId",
type: "string",
title: "Hide App by ID",
description: "Hide apps by their respective ID, as a comma-separated list.",
options: {
placeholder: "1302143410907648071, 1302132259368861759",
},
},
{
parameter: "hideDiscrim",
type: "boolean",
title: "Hide Discriminator",
description: "Hides your discriminator. (DEPRECATED, RIP)",
deprecated: true,
},
].sort((a, b) => b.type.localeCompare(a.type)) as IParameterInfo;

View File

@@ -1,6 +1,6 @@
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL, {
const redis = new Redis(process.env.REDIS_URL!, {
connectTimeout: 1000,
lazyConnect: false,
maxRetriesPerRequest: 1,

663
src/utils/renderCard.tsx Normal file
View File

@@ -0,0 +1,663 @@
"use server";
import { Badges } from "#/public/assets/badges/BadgesEncoded";
import { getFlags, renderToStaticMarkup } from "@/utils/helpers";
import * as LanyardTypes from "@/utils/LanyardTypes";
import { encodeBase64 } from "@/utils/toBase64";
import { DetailedHTMLProps, HTMLAttributes } from "react";
export type Parameters = {
theme?: string;
bg?: string;
clanbg?: string;
animated?: string;
animatedDecoration?: string;
hideDiscrim?: string;
hideStatus?: string;
hideTimestamp?: string;
hideBadges?: string;
hideProfile?: string;
hideActivity?: string;
hideSpotify?: string;
hideClan?: string;
hideDecoration?: string;
ignoreAppId?: string;
showDisplayName?: string;
borderRadius?: string;
idleMessage?: string;
};
const parseBool = (string: string | undefined): boolean => (string === "true" ? true : false);
const parseAppId = (string: string | undefined): Array<string> => {
if (string === undefined) return [];
return string.split(",");
};
const elapsedTime = (timestamp: any): string => {
let startTime = timestamp;
let endTime = Number(new Date());
let difference = (endTime - startTime) / 1000;
// we only calculate them, but we don't display them.
// this fixes a bug in the Discord API that does not send the correct timestamp to presence.
let daysDifference = Math.floor(difference / 60 / 60 / 24);
difference -= daysDifference * 60 * 60 * 24;
let hoursDifference = Math.floor(difference / 60 / 60);
difference -= hoursDifference * 60 * 60;
let minutesDifference = Math.floor(difference / 60);
difference -= minutesDifference * 60;
let secondsDifference = Math.floor(difference);
return `${hoursDifference >= 1 ? ("0" + hoursDifference).slice(-2) + ":" : ""}${("0" + minutesDifference).slice(
-2,
)}:${("0" + secondsDifference).slice(-2)}`;
};
async function renderCard(body: LanyardTypes.Root, params: Parameters): Promise<string> {
let { data } = body;
let avatarBorderColor: string = "#747F8D",
avatarExtension: string = "webp",
statusExtension: string = "webp",
activity: any = false,
backgroundColor: string = "1a1c1f",
theme = "dark",
borderRadius = "10px",
idleMessage = "I'm not currently doing anything!";
let hideStatus = parseBool(params.hideStatus);
let hideTimestamp = parseBool(params.hideTimestamp);
let hideBadges = parseBool(params.hideBadges);
let hideProfile = parseBool(params.hideProfile);
let hideActivity = params.hideActivity ?? "false";
let hideSpotify = parseBool(params.hideSpotify);
let hideClan = parseBool(params.hideClan);
let hideDecoration = parseBool(params.hideDecoration);
let ignoreAppId = parseAppId(params.ignoreAppId);
let hideDiscrim = parseBool(params.hideDiscrim);
let showDisplayName = parseBool(params.showDisplayName);
if (!data.discord_user.avatar_decoration_data) hideDecoration = true;
if (parseBool(params.hideDiscrim) || body.data.discord_user.discriminator === "0") hideDiscrim = true;
if (!body.data.discord_user.clan) hideClan = true;
if (data.activities[0]?.emoji?.animated) statusExtension = "gif";
if (data.discord_user.avatar && data.discord_user.avatar.startsWith("a_")) avatarExtension = "gif";
if (params.animated === "false") avatarExtension = "webp";
if (params.theme === "light") {
backgroundColor = "eee";
theme = "light";
}
if (params.bg) backgroundColor = params.bg;
let clanBackgroundColor: string = theme === "light" ? "#e0dede" : "#111214";
if (params.clanbg) clanBackgroundColor = params.clanbg;
if (params.idleMessage) idleMessage = params.idleMessage;
if (params.borderRadius) borderRadius = params.borderRadius;
let avatar: string;
if (data.discord_user.avatar) {
avatar = await encodeBase64(
`https://cdn.discordapp.com/avatars/${data.discord_user.id}/${
data.discord_user.avatar
}.${avatarExtension}?size=${avatarExtension === "gif" ? "64" : "256"}`,
);
} else {
avatar = await encodeBase64(
`https://cdn.discordapp.com/embed/avatars/${
data.discord_user.discriminator === "0"
? Number(BigInt(data.discord_user.id) >> BigInt(22)) % 6
: Number(data.discord_user.discriminator) % 5
}.png`,
);
}
let clanBadge: string;
if (data.discord_user.clan) {
clanBadge = await encodeBase64(
`https://cdn.discordapp.com/clan-badges/${data.discord_user.clan.identity_guild_id}/${data.discord_user.clan.badge}.png?size=16`,
);
}
let avatarDecoration: string;
if (data.discord_user.avatar_decoration_data) {
avatarDecoration = await encodeBase64(
`https://cdn.discordapp.com/avatar-decoration-presets/${data.discord_user.avatar_decoration_data.asset}.png?size=64&passthrough=${params.animatedDecoration || "true"}`,
);
}
switch (data.discord_status) {
case "online":
avatarBorderColor = "#43B581";
break;
case "idle":
avatarBorderColor = "#FAA61A";
break;
case "dnd":
avatarBorderColor = "#F04747";
break;
case "offline":
avatarBorderColor = "#747F8D";
break;
}
let flags: string[] = getFlags(data.discord_user.public_flags);
if (data.discord_user.avatar && data.discord_user.avatar.includes("a_")) flags.push("Nitro");
let userStatus: Record<string, any> | null = null;
if (data.activities[0] && data.activities[0].type === 4) userStatus = data.activities[0];
const activities = data.activities
// Filter only type 0
.filter(activity => activity.type === 0)
// Filter ignored app ID
.filter(activity => !ignoreAppId.includes(activity.application_id ?? ""));
// Take the highest one
activity = Array.isArray(activities) ? activities[0] : activities;
// Calculate height of parent SVG element
const svgHeight = (): string => {
if (hideProfile) return "130";
if (hideActivity === "true") return "91";
if (hideActivity === "whenNotUsed" && !activity && !data.listening_to_spotify) return "91";
if (hideSpotify && data.listening_to_spotify) return "210";
return "210";
};
// Calculate height of main div element
const divHeight = (): string => {
if (hideProfile) return "120";
if (hideActivity === "true") return "81";
if (hideActivity === "whenNotUsed" && !activity && !data.listening_to_spotify) return "81";
if (hideSpotify && data.listening_to_spotify) return "200";
return "200";
};
const ForeignDiv = (props: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> & { xmlns: string }) => (
<div {...props}>{props.children}</div>
);
const renderedSVG = (
<svg xmlns="http://www.w3.org/2000/svg" width="410px" height={svgHeight()}>
<defs>
<style>
{`.hover-opacity:hover {
opacity: 0.25;
}
.transition {
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 200ms;
}`}
</style>
</defs>
<foreignObject x="0" y="0" width="410" height={svgHeight()}>
<ForeignDiv
xmlns="http://www.w3.org/1999/xhtml"
style={{
position: "absolute",
width: "400px",
height: `${divHeight()}px`,
inset: 0,
backgroundColor: `#${backgroundColor}`,
color: theme === "dark" ? "#fff" : "#000",
fontFamily: `'Century Gothic', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`,
fontSize: "16px",
display: "flex",
flexDirection: "column",
padding: "5px",
borderRadius: borderRadius,
}}
>
{!hideProfile ? (
<div
style={{
width: "400px",
height: "100px",
inset: 0,
display: "flex",
flexDirection: "row",
paddingBottom: "5px",
borderBottom:
hideActivity !== "false" && !activity && !data.listening_to_spotify
? ""
: `solid 0.5px ${theme === "dark" ? "hsl(0, 0%, 100%, 10%)" : "hsl(0, 0%, 0%, 10%)"}`,
}}
>
<div
style={{
display: "flex",
position: "relative",
flexDirection: "row",
height: "80px",
width: "80px",
}}
>
<img
src={`data:image/png;base64,${avatar}`}
alt="User Avatar"
style={{
borderRadius: "50%",
width: "50px",
height: "50px",
position: "relative",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
/>
{hideDecoration || !data.discord_user.avatar_decoration_data ? null : (
<>
<img
src={`data:image/png;base64,${avatarDecoration!}`}
alt="Avatar Decoration"
style={{
display: "block",
width: "64px",
height: "64px",
position: "absolute",
top: " 50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
className="hover-opacity transition"
/>
<span
style={{
position: "absolute",
bottom: "14px",
right: "14px",
height: "13px",
width: "13px",
backgroundColor: avatarBorderColor,
borderRadius: "50%",
border: `3px solid #${backgroundColor}`,
}}
/>
</>
)}
</div>
<div
style={{
height: "80px",
width: "260px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
}}
>
<div
style={{
display: "flex",
flexDirection: "row",
height: "25px",
}}
>
<h1
style={{
fontSize: "1.15rem",
margin: "0 12px 0 0",
whiteSpace: "nowrap",
}}
>
{showDisplayName && data.discord_user.global_name
? data.discord_user.global_name
: data.discord_user.username}
{!hideDiscrim && !showDisplayName ? (
<span style={{ color: theme === "dark" ? "#ccc" : "#666", fontWeight: "lighter" }}>
#{data.discord_user.discriminator}
</span>
) : null}
</h1>
{hideClan || (!data.discord_user.clan?.tag && !data.discord_user.clan?.badge) ? null : (
<span
style={{
backgroundColor: clanBackgroundColor,
borderRadius: " 0.375rem",
paddingLeft: "0.5rem",
paddingRight: "0.5rem",
marginLeft: "-6px",
marginRight: "12px",
display: "flex",
alignItems: "center",
gap: "0.25rem",
fontSize: "16px",
fontWeight: "500",
fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`,
height: "100%",
}}
>
<img src={`data:image/png;base64,${clanBadge!}`} alt="Clan Badge" />
<p style={{ marginBottom: "1.1rem" }}>{data.discord_user.clan!.tag}</p>
</span>
)}
{!!hideBadges
? null
: flags.map(v => (
<img
key={v}
alt={v}
src={`data:image/png;base64,${Badges[v]}`}
style={{
width: "auto",
height: "20px",
position: "relative",
top: "50%",
transform: "translate(0%, -50%)",
marginRight: "7px",
}}
/>
))}
</div>
{showDisplayName ? (
<h2
style={{
fontSize: "0.95rem",
margin: 0,
whiteSpace: "nowrap",
fontWeight: "400",
}}
>
{data.discord_user.username}
</h2>
) : null}
{userStatus && !hideStatus ? (
<p
style={{
fontSize: "0.9rem",
margin: 0,
color: theme === "dark" ? "#aaa" : "#333",
fontWeight: 400,
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
}}
>
{userStatus.emoji?.id ? (
<img
src={`data:image/png;base64,${await encodeBase64(
`https://cdn.discordapp.com/emojis/${userStatus.emoji.id}.${statusExtension}`,
)}`}
alt="User Status Emoji"
style={{
width: "15px",
height: "15px",
position: "relative",
top: "10px",
transform: "translate(0%, -50%)",
margin: "0 2px 0 0",
}}
/>
) : null}
{userStatus.state && userStatus.emoji?.name && !userStatus.emoji.id
? `${userStatus.emoji.name} ${userStatus.state}`
: userStatus.state
? userStatus.state
: !userStatus.state && userStatus.emoji?.name && !userStatus.emoji.id
? userStatus.emoji.name
: null}
</p>
) : null}
</div>
</div>
) : null}
{activity ? (
<div
style={{
display: "flex",
flexDirection: "row",
height: "120px",
marginLeft: "15px",
fontSize: "0.75rem",
paddingTop: "18px",
}}
>
<div
style={{
marginRight: "15px",
width: "auto",
height: "auto",
}}
>
{activity.assets?.large_image ? (
<img
src={`data:image/png;base64,${await encodeBase64(
activity.assets.large_image.startsWith("mp:external/")
? `https://media.discordapp.net/external/${activity.assets.large_image.replace("mp:external/", "")}`
: `https://cdn.discordapp.com/app-assets/${activity.application_id}/${activity.assets.large_image}.webp`,
)}`}
alt="Activity Large Image"
style={{
width: "80px",
height: "80px",
border: "solid 0.5px #222",
borderRadius: "10px",
}}
/>
) : (
<img
src={`data:image/png;base64,${await encodeBase64(
`https://lanyard-profile-readme.vercel.app/assets/unknown.png`,
)}`}
alt="Unknown Icon"
style={{
width: "70px",
height: "70px",
marginTop: "4px",
filter: "invert(100)",
}}
/>
)}
{activity.assets?.small_image ? (
<img
src={`data:image/png;base64,${await encodeBase64(
activity.assets.small_image.startsWith("mp:external/")
? `https://media.discordapp.net/external/${activity.assets.small_image.replace("mp:external/", "")}`
: `https://cdn.discordapp.com/app-assets/${activity.application_id}/${activity.assets.small_image}.webp`,
)}`}
alt="Activity Small Image"
style={{
width: "30px",
height: "30px",
borderRadius: "50%",
marginLeft: "-26px",
marginBottom: "-8px",
}}
/>
) : null}
</div>
<div
style={{
color: "#999",
marginTop: activity.timestamps?.start && !hideTimestamp ? "-6px" : "5px",
lineHeight: "1",
width: "279px",
}}
>
<p
style={{
color: theme === "dark" ? "#fff" : "#000",
fontSize: "0.85rem",
fontWeight: "bold",
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
height: "15px",
margin: "7px 0",
}}
>
{activity.name}
</p>
{activity.details ? (
<p
style={{
color: theme === "dark" ? "#ccc" : "#777",
overflow: "hidden",
whiteSpace: "nowrap",
fontSize: "0.85rem",
textOverflow: "ellipsis",
height: "15px",
margin: "7px 0",
}}
>
{activity.details}
</p>
) : null}
{activity.state ? (
<p
style={{
color: theme === "dark" ? "#ccc" : "#777",
overflow: "hidden",
whiteSpace: "nowrap",
fontSize: "0.85rem",
textOverflow: "ellipsis",
height: "15px",
margin: "7px 0",
}}
>
{activity.state}
{activity.party?.size ? ` (${activity.party.size[0]} of ${activity.party.size[1]})` : null}
</p>
) : null}
{activity.timestamps?.start && !hideTimestamp ? (
<p
style={{
color: theme === "dark" ? "#ccc" : "#777",
overflow: "hidden",
whiteSpace: "nowrap",
fontSize: "0.85rem",
textOverflow: "ellipsis",
height: "15px",
margin: "7px 0",
}}
>
{elapsedTime(new Date(activity.timestamps.start).getTime())} elapsed
</p>
) : null}
</div>
</div>
) : null}
{data.listening_to_spotify &&
!activity &&
!hideSpotify &&
data.activities[Object.keys(data.activities).length - 1].type === 2 ? (
<div
style={{
display: "flex",
flexDirection: "row",
height: "120px",
marginLeft: "15px",
fontSize: "0.8rem",
paddingTop: "18px",
}}
>
<img
src={await (async () => {
const album = await encodeBase64(data.spotify.album_art_url);
if (album) return `data:image/png;base64,${album}`;
return "https://lanyard-profile-readme.vercel.app/assets/unknown.png";
})()}
alt="Album Cover"
style={{
border: data.spotify.album_art_url ? "border: solid 0.5px #222" : undefined,
filter: !data.spotify.album_art_url ? "invert(100)" : undefined,
width: "80px",
height: "80px",
borderRadius: "10px",
marginRight: "15px",
}}
/>
<div
style={{
color: "#999",
marginTop: "-3px",
lineHeight: "1",
width: "279px",
}}
>
<p
style={{
fontSize: "0.75rem",
fontWeight: "bold",
color: theme === "dark" ? "#1CB853" : "#0d943d",
marginBottom: "15px",
}}
>
LISTENING TO SPOTIFY...
</p>
<p
style={{
height: "15px",
color: theme === "dark" ? "#fff" : "#000",
fontWeight: "bold",
fontSize: "0.85rem",
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
margin: "7px 0",
}}
>
{data.spotify.song}
</p>
<p
style={{
margin: "7px 0",
height: "15px",
overflow: "hidden",
whiteSpace: "nowrap",
fontSize: "0.85rem",
textOverflow: "ellipsis",
color: theme === "dark" ? "#ccc" : "#777",
}}
>
By {data.spotify.artist}
</p>
</div>
</div>
) : null}
{!activity && (!data.listening_to_spotify || hideSpotify) && hideActivity === "false" ? (
<div
style={{
display: "flex",
flexDirection: "row",
height: "150px",
justifyContent: "center",
alignItems: "center",
}}
>
<p
style={{
fontStyle: "italic",
fontSize: "0.8rem",
color: theme === "dark" ? "#aaa" : "#444",
height: "auto",
textAlign: "center",
}}
>
{idleMessage}
</p>
</div>
) : null}
</ForeignDiv>
</foreignObject>
</svg>
);
return renderToStaticMarkup(renderedSVG);
}
export default renderCard;

View File

@@ -4,6 +4,8 @@ const EPOCH = 1420070400000; // Discord's EPOCH
export function isSnowflake(snowflake: number | string): boolean {
snowflake = Number(snowflake);
return (
Number.isInteger(+snowflake) && snowflake > 4194304 && !isNaN(new Date(snowflake / 4194304 + EPOCH).getTime())
Number.isInteger(+snowflake) &&
snowflake > 4194304 &&
!isNaN(new Date(snowflake / 4194304 + EPOCH).getTime())
);
}

18
src/utils/toBase64.ts Normal file
View File

@@ -0,0 +1,18 @@
export const encodeBase64 = async (url: string): Promise<string> => {
let response = "";
try {
response = await fetch(url, {
cache: "no-store",
})
.then((res) => res.blob())
.then(async (blob) => {
const buffer = Buffer.from(await blob.arrayBuffer());
return buffer.toString("base64");
});
} catch (e) {
console.log(e);
}
return response;
};

20
tailwind.config.ts Normal file
View File

@@ -0,0 +1,20 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: ["class"],
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [require("tailwindcss-animate")],
};
export default config;

View File

@@ -1,6 +1,5 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
@@ -9,22 +8,36 @@
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
],
"#/*": [
"./*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"pages/_document.tsx"
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
}

2661
yarn.lock

File diff suppressed because it is too large Load Diff