feat: migrate to the new system.

This commit is contained in:
Hexagonn
2024-10-20 19:44:03 +07:00
parent ff86f2afde
commit be11864c21
68 changed files with 1293 additions and 2752 deletions

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"
}
}

12
.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,11 @@ yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -1 +1 @@
src/renderCard.tsx
src/utils/renderCard.tsx

View File

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

4
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"editor.tabSize": 4,
"prettier.tabWidth": 4
}

View File

@@ -1,4 +1,5 @@
<!-- markdownlint-disable -->
# lanyard-profile-readme
🏷️ Utilize Lanyard to display your Discord Presence in your GitHub Profile
@@ -25,75 +26,77 @@ When others click it, they will be directed to your actual Discord profile. Neat
There are a few options to customize this display using query parameters:
### ___Theme___
### **_Theme_**
Append the query param `theme=:theme` to the end of the URL, replacing `:theme` with either `light` or `dark`. This will change the background and the font colors, but the background can be overridden with the ___Background Color___ parameter.
Append the query param `theme=:theme` to the end of the URL, replacing `:theme` with either `light` or `dark`. This will change the background and the font colors, but the background can be overridden with the **_Background Color_** parameter.
### ___Background Color___
### **_Background Color_**
Append the query param `bg=:color` to the end of the URL, replacing `:color` with a hex color of your choice (omit the #)
### ___Border Radius___
### **_Border Radius_**
Append the query param `borderRadius=:radius` to the end of the URL, replacing `:radius` with a radius of your choice. (default `10px`)
### ___Toggle Animated Avatar___
### **_Toggle Animated Avatar_**
If you have an animated avatar, append the query param `animated=:bool` to the end of the URL, replacing `:bool` with `true` or `false`. This is set to `true` by default.
### ___Custom Idle Message___
### **_Custom Idle Message_**
If you don't want the default "`I'm not currently doing anything!`" as your idle message, you can change it by appending `idleMessage=:yourmessage` to the end of the URL.
If you don't want the default "`I'm not currently doing anything!`" as your idle message, you can change it by appending `idleMessage=:yourmessage` to the end of the URL.
### ___Show Display Name___
### **_Show Display Name_**
If you'd like to show your global display name as well as your username, append the query param `showDisplayName=true` to the end of the URL. This is set to `false` by default.
If you'd like to show your global display name as well as your username, append the query param `showDisplayName=true` to the end of the URL. This is set to `false` by default.
### ___Avatar Decoration___
### **_Avatar Decoration_**
#### **_Hide Avatar Decoration_**
#### ___Hide Avatar Decoration___
If you don't want people seeing your Avatar Decoration, append the query param `hideDecoration=true` to the end of the URL. Your Avatar Decoration is shown by default if you have one.
#### ___Toogle Animated Avatar Decoration___
#### **_Toogle Animated Avatar Decoration_**
If you have an Animated Avatar Decoration, append the query param `animatedDecoration=:bool` to the end of the URL, replacing `:bool` with `true` or `false`. This is set to `true` by default.
### ___Hide Status___
### **_Hide Status_**
If you don't want people seeing your status, append the query param `hideStatus=true` to the end of the URL. Your status is shown by default if you have one.
If you don't want people seeing your status, append the query param `hideStatus=true` to the end of the URL. Your status is shown by default if you have one.
### ___Hide Elapsed Time___
### **_Hide Elapsed Time_**
If you don't want people seeing the elapsed time on an activity, append the query param `hideTimestamp=true` to the end of the URL. Elapsed time is shown by default.
### ___Hide Clan Tag___
### **_Hide Clan Tag_**
If you don't want people seeing your Clan Tag (formerly known as Guilds), append the query param `hideClan=true` to the end of the URL. Clan Tag is shown by default.
### ___Hide Badges___
### **_Hide Badges_**
If you don't want people seeing the badges you have on Discord, append the query param `hideBadges=true` to the end of the URL. Badges are shown by default.
### ___Hide Profile___
### **_Hide Profile_**
If you don't want people seeing the profile you have on Discord, append the query param `hideProfile=true` to the end of the URL. Profile are shown by default.
### ___Hide Activity___
### **_Hide Activity_**
If you don't want people seeing the your activity, append the query param `hideActivity=true` to the end of the URL or use `hideActivity=whenNotUsed` to hide activity section when there's no activity to display. Activity are shown by default.
### ___Hide Spotify___
### **_Hide Spotify_**
If you don't want people seeing your Spotify activity, append the query param `hideSpotify=true` to the end of the URL. Spotify activity is shown by default.
### ___Hide App by ID___
### **_Hide App by ID_**
If you don't want display a specific application, append the query param `ignoreAppId=:app_id` to the end of the URL, IDs separate by `,`.
### ___Hide Discriminator___ (DEPRECATED soon)
### **_Hide Discriminator_** (DEPRECATED soon)
If you don't want people seeing your discriminator (most likely for privacy reasons), append the query param `hideDiscrim=true` to the end of the URL. Your discriminator is shown by default.
If you don't want people seeing your discriminator (most likely for privacy reasons), append the query param `hideDiscrim=true` to the end of the URL. Your discriminator is shown by default.
## ___Example URL and result___
## **_Example URL and result_**
```
[![Discord Presence](https://lanyard-profile-readme.vercel.app/api/94490510688792576?theme=light&bg=809ecf&animated=false&hideDiscrim=true&borderRadius=30px&idleMessage=Probably%20doing%20something%20else...)](https://discord.com/users/94490510688792576)

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.

4
next.config.mjs Normal file
View File

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

9
old/.prettierrc Normal file
View File

@@ -0,0 +1,9 @@
{
"quoteProps": "consistent",
"printWidth": 120,
"bracketSpacing": true,
"singleQuote": false,
"useTabs": false,
"arrowParens": "avoid",
"tabWidth": 4
}

35
old/package.json Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/escape-html": "^1.0.1",
"@types/ioredis": "^4.28.8",
"@types/styled-components": "^5.1.10",
"axios": "^0.21.1",
"escape-html": "^1.0.3",
"framer-motion": "^4.1.17",
"image-to-base64": "^2.2.0",
"ioredis": "^4.28.5",
"next": "14.2.15",
"react": "18.3.1",
"react-dom": "18.3.1",
"styled-components": "^5.3.0",
"use-smooth-count": "^0.3.0"
},
"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": "^14.2.15",
"prettier": "^2.3.1",
"typescript": "5.6.3"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 799 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="700.000000pt" height="700.000000pt" viewBox="0 0 700.000000 700.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.14, written by Peter Selinger 2001-2017
</metadata>
<g transform="translate(0.000000,700.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M3087 6923 c-19 -8 -213 -195 -472 -453 l-440 -440 -670 -3 c-369 -2
-681 -7 -695 -10 -14 -4 -38 -10 -55 -13 -64 -14 -157 -65 -211 -116 -55 -52
-112 -147 -128 -213 -5 -16 -11 -39 -14 -50 -4 -11 -8 -519 -9 -1128 -4 -1222
-5 -1207 57 -1334 37 -75 -24 -12 1017 -1060 2095 -2111 1967 -1985 2063
-2031 112 -54 192 -72 305 -67 50 2 106 6 125 10 61 12 167 61 232 108 95 68
2085 2071 2127 2141 36 60 76 153 86 201 16 75 13 230 -6 303 -42 157 -91 227
-315 447 -89 88 -346 340 -569 560 -224 220 -495 487 -603 594 -108 106 -401
394 -651 640 -973 958 -934 920 -987 947 -42 22 -120 50 -169 59 -25 5 -257
15 -355 15 -20 0 29 54 277 303 165 166 307 316 315 332 33 69 13 170 -43 222
-55 51 -141 65 -212 36z m-1703 -1686 c-44 -48 -59 -84 -58 -144 1 -62 16 -97
61 -139 82 -77 186 -70 281 19 l55 52 -6 -62 c-12 -138 -115 -245 -256 -266
-50 -7 -133 14 -185 47 -178 114 -175 375 5 488 28 18 121 48 128 42 3 -3 -9
-19 -25 -37z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

31
old/tsconfig.json Normal file
View File

@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"pages/_document.tsx"
],
"exclude": [
"node_modules"
]
}

View File

@@ -1,35 +1,35 @@
{
"name": "next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/escape-html": "^1.0.1",
"@types/ioredis": "^4.28.8",
"@types/styled-components": "^5.1.10",
"axios": "^0.21.1",
"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"
},
"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"
}
"name": "app-router",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/escape-html": "^1.0.4",
"@types/image-to-base64": "^2.1.2",
"escape-html": "^1.0.3",
"image-to-base64": "^2.2.0",
"ioredis": "^5.4.1",
"next": "14.2.15",
"react": "^18",
"react-dom": "^18",
"swr": "^2.2.5",
"use-smooth-count": "^1.0.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.15",
"postcss": "^8",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

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

@@ -0,0 +1,85 @@
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: { id: string[] } },
) {
const userId = 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}`,
).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

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

@@ -0,0 +1,108 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #010103;
--foreground: #171717;
}
body {
color: var(--foreground);
background: var(--background);
font-family: "Poppins", sans-serif;
}
.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);
}
}
.output {
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;
}
.action {
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;
}
}
.stat {
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;
}
}

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

@@ -0,0 +1,35 @@
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:
"Utilize Lanyard to display your Discord Presence in your GitHub Profile",
openGraph: {
title: "Lanyard for GitHub Profile",
description:
"Utilize Lanyard to display your Discord Presence in your GitHub Profile",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${poppins.className} antialiased`}>
{children}
</body>
</html>
);
}

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

@@ -0,0 +1,75 @@
"use client";
import Image from "next/image";
import React, { useState, useEffect, useRef } from "react";
import { useSmoothCount } from "use-smooth-count";
import useSWR from "swr";
import { getUserCount } from "@/utils/actions";
export default function Home() {
const [userId, setUserId] = useState<null | string>(null);
const [userError, setUserError] = useState<string>();
const [copyState, setCopyState] = useState("Copy");
const userCount = useSWR("getUserCount", getUserCount);
const countRef = useRef<HTMLDivElement | null>(null);
const counter = useSmoothCount({
ref: countRef,
target: userCount.data || 0,
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);
};
return (
<>
<main className="flex min-h-screen max-w-[100vw] flex-col items-center">
<div className="mt-16 w-[80%] max-w-[28rem] rounded-md">
<p className="my-2 text-left text-3xl font-semibold text-[#cecece]">
lanyard profile readme 🏷
</p>
<p className="text-base text-[#aaabaf]">
Utilize Lanyard to display your Discord Presence in your
GitHub Profile
</p>
<br />
<input
className="input"
onChange={(e) => setUserId(e.target.value)}
placeholder="Enter your Discord ID"
/>
{userId && (
<>
<div className="output">
[![Discord Presence]({window.location.origin}
/api/{userId})](https://discord.com/users/
{userId})
</div>
<button className="action" onClick={copy}>
{copyState}
</button>
<button className="action">Option</button>
</>
)}
</div>
</main>
<footer className="stat">
Lanyard Profile Readme has{" "}
<div
style={{ fontWeight: "bold", width: "3.2rem" }}
ref={countRef}
/>{" "}
total users!
</footer>
</>
);
}

95
src/utils/LanyardTypes.ts Normal file
View File

@@ -0,0 +1,95 @@
//thanks alistair @ uwu.red
export interface Root {
success: boolean;
data: Data;
}
export interface Data {
spotify: Spotify;
listening_to_spotify: boolean;
discord_user: DiscordUser;
discord_status: string;
activities: Activity[];
active_on_discord_mobile: boolean;
active_on_discord_desktop: boolean;
}
export interface Spotify {
track_id: string;
timestamps: Timestamps;
song: string;
artist: string;
album_art_url: string;
album: string;
}
export interface Timestamps {
start: number;
end: number;
}
export interface DiscordUser {
username: string;
public_flags: number;
id: string;
discriminator: string;
avatar: string;
global_name: string;
display_name: string;
clan: ClanTag | null;
avatar_decoration_data: AvatarDecoration | null;
}
export interface ClanTag {
tag: string;
badge: string;
identity_enabled: boolean;
identity_guild_id: number;
}
export interface AvatarDecoration {
sku_id: string;
asset: string;
expires_at: number;
}
export interface Activity {
type: number;
state: string;
name: string;
id: string;
emoji?: Emoji;
created_at: number;
application_id?: string;
timestamps?: Timestamps2;
sync_id?: string;
session_id?: string;
party?: Party;
flags?: number;
details?: string;
assets?: Assets;
buttons?: string[];
}
export interface Emoji {
name: string;
id: number;
animated: boolean;
}
export interface Timestamps2 {
start: number;
end?: number;
}
export interface Party {
id: string;
}
export interface Assets {
small_text?: string;
small_image?: string;
large_text: string;
large_image: string;
}

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;
}

19
src/utils/getFlags.ts Normal file
View File

@@ -0,0 +1,19 @@
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;
};

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

@@ -0,0 +1,9 @@
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL, {
connectTimeout: 1000,
lazyConnect: false,
maxRetriesPerRequest: 1,
});
export default redis;

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

@@ -0,0 +1,578 @@
// probably the messiest code i've ever written but it works so :)
import { Badges } from "#/public/assets/badges/BadgesEncoded";
import { getFlags } from "@/utils/getFlags";
import * as LanyardTypes from "@/utils/LanyardTypes";
import { encodeBase64 } from "@/utils/toBase64";
import escape from "escape-html";
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) => {
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;

11
src/utils/snowflake.ts Normal file
View File

@@ -0,0 +1,11 @@
const EPOCH = 1420070400000; // Discord's EPOCH
// Snowflakes will never be a string
export function isSnowflake(snowflake: number | string): boolean {
snowflake = Number(snowflake);
return (
Number.isInteger(+snowflake) &&
snowflake > 4194304 &&
!isNaN(new Date(snowflake / 4194304 + EPOCH).getTime())
);
}

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

@@ -0,0 +1,13 @@
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;
};

19
tailwind.config.ts Normal file
View File

@@ -0,0 +1,19 @@
import type { Config } from "tailwindcss";
const config: Config = {
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: [],
};
export default config;

View File

@@ -1,30 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"lib": ["dom", "dom.iterable", "esnext"],
"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/*"],
"#/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"pages/_document.tsx"
],
"exclude": [
"node_modules"
]
}
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

2661
yarn.lock

File diff suppressed because it is too large Load Diff