Compare commits

..

19 commits
main ... main

Author SHA1 Message Date
9d6b9e40a7
fix missing av decoration, missed when moving to js 2025-05-16 18:53:15 -04:00
bf52c02122
remove uneeded 2025-05-14 10:36:19 -04:00
fca71334e9
fix listening 2025-05-14 10:35:46 -04:00
11ab56b9b3
forgot readme 2025-05-12 18:52:43 -04:00
a25aff0e24
forgot to stage 2025-05-12 18:49:53 -04:00
aa24c979ee
add robots txt route, verifiy required env vars func, fix issue with reviewdb badges and emojis 2025-05-12 18:49:42 -04:00
dbdb59f48b
fix the scroll and "page" logic 2025-05-10 13:05:10 -04:00
453a79a4e4
to 24h 2025-05-10 12:54:57 -04:00
87b09af73e
forgot readme 2025-05-10 12:51:11 -04:00
9aa58ae23f
add review db, fix issues with spamming css url and readme whenever status updated 2025-05-10 12:46:58 -04:00
5ad5d7181f
add option for users to opt out 2025-05-07 15:21:39 -04:00
ba67ba55e3
fix issue with indef loading for unkown users 2025-05-07 15:18:37 -04:00
784330b5a6
fix rain,snow,stars, activity title 2025-05-04 11:28:40 -04:00
60a52df5fa
idk how i forgot the favicon 2025-05-03 07:35:48 -04:00
a4f139406c
reformat the html for better seo? 2025-05-03 07:28:23 -04:00
167d989600
add plausible support 2025-05-03 07:07:26 -04:00
dbe894a568
add to readme 2025-05-02 13:15:30 -04:00
2330953c33
fix issue with empty badge loading 2025-05-01 20:20:55 -04:00
88b3783451
should fix transparent smallimages for activities 2025-05-01 20:17:48 -04:00
16 changed files with 735 additions and 174 deletions

View file

@ -12,5 +12,12 @@ LANYARD_INSTANCE=https://lanyard.rest
# Required if you want to enable badges
BADGE_API_URL=http://localhost:8081
# Required if you want to enable reviews from reviewdb
REVIEW_DB=true
# https://www.steamgriddb.com/api/v2, if you want games to have images
STEAMGRIDDB_API_KEY=steamgrid_api_key
# https://plausible.io
PLAUSIBLE_SCRIPT_HTML=''

1
.gitignore vendored
View file

@ -3,3 +3,4 @@ bun.lock
.env
logs/
.vscode/
robots.txt

View file

@ -2,6 +2,9 @@
A cool little web app that shows your Discord profile, current activity, and more. Built with Bun.
# Preview
https://creations.works
---
## Requirements
@ -26,7 +29,7 @@ https://git.creations.works/creations/badgeAPI
### 4. SteamGridDB
>You only have to use this if you want to fetch game icons that Discord doesnt provide:
>Only needed if you want to fetch game icons that Discord doesnt provide:
https://www.steamgriddb.com/api/v2
---
@ -59,7 +62,9 @@ cp .env.example .env
| `LANYARD_USER_ID` | Your Discord user ID, for the default page |
| `LANYARD_INSTANCE` | Endpoint of the Lanyard instance |
| `BADGE_API_URL` | Badge API URL ([badgeAPI](https://git.creations.works/creations/badgeAPI)) |
| `REVIEW_DB` | Enables showing reviews from reviewdb on user pages |
| `STEAMGRIDDB_API_KEY` | SteamGridDB API key for fetching game icons |
| `ROBOTS_FILE` | If there it uses the file in /robots.txt route, requires a valid path |
#### Optional Lanyard KV Variables (per-user customization)
@ -73,6 +78,8 @@ These can be defined in Lanyard's KV store to customize the page:
| `badges` | Enables badge fetching (`true` / `false`) |
| `readme` | URL to a README displayed on the profile (`.md` or `.html`) |
| `css` | URL to a css to change styles on the page, no import or require allowed |
| `optout` | Allows users to stop sharing there profile on the website (`true` / `false`) |
| `reviews` | Enables reviews from reviewdb (`true` / `false`) |
---
@ -84,6 +91,28 @@ bun run start
---
## Optional: Analytics with Plausible
You can enable [Plausible Analytics](https://plausible.io) tracking by setting a script snippet in your environment.
### `.env` Variable
| Variable | Description |
|-------------------------|------------------------------------------------------------------------|
| `PLAUSIBLE_SCRIPT_HTML` | Full `<script>` tag(s) to inject into the `<head>` for analytics |
#### Example
```env
PLAUSIBLE_SCRIPT_HTML='<script defer data-domain="example.com" src="https://plausible.example.com/js/script.js"></script><script>window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>'
```
- The script will only be injected if this variable is set.
- Plausible provides the correct script when you add a domain.
- Be sure to wrap it in single quotes (`'`) so it works in `.env`.
---
## Docker Support
### Build & Start with Docker Compose
@ -96,6 +125,19 @@ Make sure the `.env` file is configured correctly before starting the container.
---
## Routes
These are the main public routes exposed by the server:
| Route | Description |
|---------|-----------------------------------------------------------------------------|
| `/` | Loads the profile page for the default Discord user defined in `.env` (`LANYARD_USER_ID`) |
| `/[id]` | Loads the profile page for a specific Discord user ID passed in the URL |
> Example: `https://creations.works/209830981060788225` shows the profile of that specific user.
---
## License
[BSD 3](LICENSE)

View file

@ -1,19 +1,69 @@
export const environment: Environment = {
import { resolve } from "node:path";
import { logger } from "@creations.works/logger";
const environment: Environment = {
port: Number.parseInt(process.env.PORT || "8080", 10),
host: process.env.HOST || "0.0.0.0",
development:
process.env.NODE_ENV === "development" || process.argv.includes("--dev"),
};
export const redisTtl: number = process.env.REDIS_TTL
const redisTtl: number = process.env.REDIS_TTL
? Number.parseInt(process.env.REDIS_TTL, 10)
: 60 * 60 * 1; // 1 hour
export const lanyardConfig: LanyardConfig = {
const lanyardConfig: LanyardConfig = {
userId: process.env.LANYARD_USER_ID || "",
instance: process.env.LANYARD_INSTANCE || "https://api.lanyard.rest",
instance: process.env.LANYARD_INSTANCE || "",
};
export const badgeApi: string | null = process.env.BADGE_API_URL || null;
export const steamGridDbKey: string | undefined =
process.env.STEAMGRIDDB_API_KEY;
const reviewDb = {
enabled: process.env.REVIEW_DB === "true" || process.env.REVIEW_DB === "1",
url: "https://manti.vendicated.dev/api/reviewdb",
};
const badgeApi: string | null = process.env.BADGE_API_URL || null;
const steamGridDbKey: string | undefined = process.env.STEAMGRIDDB_API_KEY;
const plausibleScript: string | null =
process.env.PLAUSIBLE_SCRIPT_HTML?.trim() || null;
const robotstxtPath: string | null = process.env.ROBOTS_FILE
? resolve(process.env.ROBOTS_FILE)
: null;
function verifyRequiredVariables(): void {
const requiredVariables = [
"HOST",
"PORT",
"LANYARD_USER_ID",
"LANYARD_INSTANCE",
];
let hasError = false;
for (const key of requiredVariables) {
const value = process.env[key];
if (value === undefined || value.trim() === "") {
logger.error(`Missing or empty environment variable: ${key}`);
hasError = true;
}
}
if (hasError) {
process.exit(1);
}
}
export {
environment,
lanyardConfig,
redisTtl,
reviewDb,
badgeApi,
steamGridDbKey,
plausibleScript,
robotstxtPath,
verifyRequiredVariables,
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 168 KiB

BIN
public/assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9 KiB

View file

@ -1,25 +0,0 @@
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 90vh;
background: #0e0e10;
color: #fff;
font-family: system-ui, sans-serif;
}
.error-container {
text-align: center;
padding: 2rem;
background: #1a1a1d;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}
.error-title {
font-size: 2rem;
margin-bottom: 1rem;
color: #ff4e4e;
}
.error-message {
font-size: 1.2rem;
opacity: 0.8;
}

View file

@ -85,6 +85,15 @@ body {
align-items: center;
}
main {
width: 100%;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
}
.open-source-logo {
width: 2rem;
height: 2rem;
@ -168,10 +177,10 @@ body {
.decoration {
position: absolute;
top: -18px;
left: -18px;
width: 164px;
height: 164px;
top: -13px;
left: -16px;
width: 160px;
height: 160px;
pointer-events: none;
}
@ -330,6 +339,25 @@ ul {
max-width: 700px;
}
.activities-section {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
max-width: 700px;
box-sizing: border-box;
padding: 0;
margin: 0;
}
.activities-section .activity-block-header {
margin: 1rem 0 .5rem;
font-size: 2rem;
font-weight: 600;
text-align: center;
}
.activities {
display: flex;
flex-direction: column;
@ -386,6 +414,7 @@ ul {
object-fit: cover;
flex-shrink: 0;
border-color: var(--card-bg);
background-color: var(--card-bg);
border-width: 2px;
border-style: solid;
@ -785,3 +814,184 @@ ul {
font-size: 0.95rem;
}
}
/* reviews */
.reviews {
width: 100%;
max-width: 700px;
margin-top: 2rem;
display: flex;
flex-direction: column;
gap: 1rem;
background-color: var(--card-bg);
padding: 1rem;
border-radius: 10px;
border: 1px solid var(--border-color);
box-sizing: border-box;
}
.reviews h2 {
margin: 0 0 1rem;
font-size: 2rem;
font-weight: 600;
text-align: center;
}
.reviews-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.review {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 1rem;
padding: 0.75rem 1rem;
border-radius: 8px;
border: 1px solid var(--border-color);
transition: background-color 0.3s ease;
}
.review:hover {
background-color: var(--card-hover-bg);
}
.review-avatar {
width: 44px;
height: 44px;
border-radius: 50%;
object-fit: cover;
flex-shrink: 0;
}
.review-body {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.review-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.review-header-inner {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
}
.review-username {
font-weight: 600;
color: var(--text-color);
}
.review-timestamp {
font-size: 0.8rem;
color: var(--text-muted);
}
.review-content {
color: var(--text-secondary);
font-size: 0.95rem;
word-break: break-word;
white-space: pre-wrap;
}
.review-badges {
display: flex;
gap: 0.3rem;
flex-wrap: wrap;
}
.emoji {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0 2px;
display: inline-block;
transition: transform 0.3s ease;
}
.emoji:hover {
transform: scale(1.2);
}
.review-content img.emoji {
vertical-align: middle;
}
@media (max-width: 600px) {
.reviews {
max-width: 100%;
padding: 1rem;
border-radius: 0;
border: none;
background-color: transparent;
}
.reviews h2 {
font-size: 1.4rem;
text-align: center;
margin-bottom: 1rem;
}
.reviews-list {
gap: 0.75rem;
}
.review {
flex-direction: column;
align-items: center;
text-align: center;
padding: 1rem;
border-radius: 0;
}
.review-avatar {
width: 64px;
height: 64px;
}
.review-body {
width: 100%;
align-items: center;
}
.review-header {
flex-direction: column;
align-items: center;
gap: 0.25rem;
}
.review-username {
font-size: 1rem;
}
.review-timestamp {
font-size: 0.75rem;
}
.review-content {
font-size: 0.9rem;
}
.review-badges {
justify-content: center;
}
.emoji {
width: 16px;
height: 16px;
}
}

View file

@ -2,10 +2,19 @@ const head = document.querySelector("head");
const userId = head?.dataset.userId;
const activityProgressMap = new Map();
const reviewURL = head?.dataset.reviewDb;
let instanceUri = head?.dataset.instanceUri;
let badgeURL = head?.dataset.badgeUrl;
let socket;
let badgesLoaded = false;
let readmeLoaded = false;
let cssLoaded = false;
const reviewsPerPage = 50;
let currentReviewOffset = 0;
let hasMoreReviews = true;
let isLoadingReviews = false;
function formatTime(ms) {
const totalSecs = Math.floor(ms / 1000);
@ -119,6 +128,108 @@ function resolveActivityImage(img, applicationId) {
return `https://cdn.discordapp.com/app-assets/${applicationId}/${img}.png`;
}
async function populateReviews(userId) {
if (!reviewURL || !userId || isLoadingReviews || !hasMoreReviews) return;
const reviewSection = document.querySelector(".reviews");
const reviewList = reviewSection?.querySelector(".reviews-list");
if (!reviewList) return;
isLoadingReviews = true;
try {
const url = `${reviewURL}/users/${userId}/reviews?flags=2&offset=${currentReviewOffset}`;
const res = await fetch(url);
const data = await res.json();
if (!data.success || !Array.isArray(data.reviews)) {
if (currentReviewOffset === 0) reviewSection.classList.add("hidden");
isLoadingReviews = false;
return;
}
const reviewsHTML = data.reviews
.map((review) => {
const sender = review.sender;
const username = sender.username;
const avatar = sender.profilePhoto;
let comment = review.comment;
comment = comment.replace(
/<(a?):\w+:(\d+)>/g,
(_, animated, id) =>
`<img src="https://cdn.discordapp.com/emojis/${id}.${animated ? "gif" : "webp"}" class="emoji" alt="emoji" />`,
);
const timestamp = review.timestamp
? new Date(review.timestamp * 1000).toLocaleString(undefined, {
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
})
: "N/A";
const badges = (sender.badges || [])
.map(
(b) =>
`<img src="${b.icon}" class="badge" title="${b.description}" alt="${b.name}" />`,
)
.join("");
return `
<li class="review">
<img class="review-avatar" src="${avatar}" alt="${username}'s avatar"/>
<div class="review-body">
<div class="review-header">
<div class="review-header-inner">
<span class="review-username">${username}</span>
<span class="review-badges">${badges}</span>
</div>
<span class="review-timestamp">${timestamp}</span>
</div>
<div class="review-content">${comment}</div>
</div>
</li>
`;
})
.join("");
if (currentReviewOffset === 0) reviewList.innerHTML = reviewsHTML;
else reviewList.insertAdjacentHTML("beforeend", reviewsHTML);
reviewSection.classList.remove("hidden");
hasMoreReviews = data.hasNextPage;
isLoadingReviews = false;
} catch (err) {
console.error("Failed to fetch reviews", err);
isLoadingReviews = false;
}
}
function setupReviewScrollObserver(userId) {
const sentinel = document.createElement("div");
sentinel.className = "review-scroll-sentinel";
document.querySelector(".reviews").appendChild(sentinel);
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMoreReviews && !isLoadingReviews) {
currentReviewOffset += reviewsPerPage;
populateReviews(userId);
}
},
{
rootMargin: "200px",
threshold: 0,
},
);
observer.observe(sentinel);
}
function buildActivityHTML(activity) {
const start = activity.timestamps?.start;
const end = activity.timestamps?.end;
@ -147,18 +258,15 @@ function buildActivityHTML(activity) {
const activityTypeMap = {
0: "Playing",
1: "Streaming",
2: "Listening",
2: "Listening to",
3: "Watching",
4: "Custom Status",
5: "Competing",
};
const activityType =
activity.name === "Spotify"
? "Listening to Spotify"
: activity.name === "TIDAL"
? "Listening to TIDAL"
: activityTypeMap[activity.type] || "Playing";
const activityType = activityTypeMap[activity.type]
? `${activityTypeMap[activity.type]}${activity.type === 2 ? ` ${activity.name}` : ""}`
: "Playing";
const activityTimestamp =
start && progress === null
@ -283,7 +391,13 @@ async function loadBadges(userId, options = {}) {
const res = await fetch(url);
const json = await res.json();
if (!res.ok || !json.badges) {
if (
!res.ok ||
!json.badges ||
Object.values(json.badges).every(
(arr) => !Array.isArray(arr) || arr.length === 0,
)
) {
target.textContent = "Failed to load badges.";
return;
}
@ -328,10 +442,13 @@ async function loadBadges(userId, options = {}) {
}
async function populateReadme(data) {
const readmeSection = document.querySelector(".readme");
if (readmeLoaded) return;
if (readmeSection && data.kv?.readme) {
const url = data.kv.readme;
const readmeSection = document.querySelector(".readme");
const kv = data.kv || {};
if (readmeSection && kv.readme) {
const url = kv.readme;
try {
const res = await fetch(`/api/readme?url=${encodeURIComponent(url)}`);
if (!res.ok) throw new Error("Failed to fetch readme");
@ -340,6 +457,7 @@ async function populateReadme(data) {
readmeSection.innerHTML = `<div class="markdown-body">${text}</div>`;
readmeSection.classList.remove("hidden");
readmeLoaded = true;
} catch (err) {
console.error("Failed to load README", err);
readmeSection.classList.add("hidden");
@ -349,9 +467,47 @@ async function populateReadme(data) {
}
}
async function updatePresence(data) {
const cssLink = data.kv?.css;
if (cssLink) {
async function updatePresence(initialData) {
if (
!initialData ||
typeof initialData !== "object" ||
initialData.success === false ||
initialData.error
) {
const loadingOverlay = document.getElementById("loading-overlay");
if (loadingOverlay) {
loadingOverlay.innerHTML = `
<div class="error-message">
<p>${initialData?.error?.message || "Failed to load presence data."}</p>
</div>
`;
loadingOverlay.style.opacity = "1";
}
return;
}
const data =
initialData?.d && Object.keys(initialData.d).length > 0
? initialData.d
: initialData;
const kv = data.kv || {};
if (kv.optout === "true") {
const loadingOverlay = document.getElementById("loading-overlay");
if (loadingOverlay) {
loadingOverlay.innerHTML = `
<div class="error-message">
<p>This user has opted out of sharing their presence.</p>
</div>
`;
loadingOverlay.style.opacity = "1";
}
return;
}
const cssLink = kv.css;
if (cssLink && !cssLoaded) {
try {
const res = await fetch(`/api/css?url=${encodeURIComponent(cssLink)}`);
if (!res.ok) throw new Error("Failed to fetch CSS");
@ -360,12 +516,13 @@ async function updatePresence(data) {
const style = document.createElement("style");
style.textContent = cssText;
document.head.appendChild(style);
cssLoaded = true;
} catch (err) {
console.error("Failed to load CSS", err);
}
}
if (!badgesLoaded && data && data.kv.badges !== "false") {
if (!badgesLoaded && data?.kv && data.kv.badges !== "false") {
loadBadges(userId, {
services: [],
seperated: true,
@ -378,6 +535,7 @@ async function updatePresence(data) {
const avatarWrapper = document.querySelector(".avatar-wrapper");
const avatarImg = avatarWrapper?.querySelector(".avatar");
const decorationImg = avatarWrapper?.querySelector(".decoration");
const usernameEl = document.querySelector(".username");
if (!data.discord_user) {
@ -409,6 +567,19 @@ async function updatePresence(data) {
}
}
if (
decorationImg &&
data.discord_user?.avatar_decoration_data &&
data.discord_user.avatar_decoration_data.asset
) {
const newDecorationUrl = `https://cdn.discordapp.com/avatar-decoration-presets/${data.discord_user.avatar_decoration_data.asset}`;
decorationImg.src = newDecorationUrl;
decorationImg.classList.remove("hidden");
} else if (decorationImg) {
decorationImg.src = "";
decorationImg.classList.add("hidden");
}
if (usernameEl) {
const username =
data.discord_user.global_name || data.discord_user.username;
@ -417,6 +588,10 @@ async function updatePresence(data) {
}
updateClanBadge(data);
if (kv.reviews !== "false") {
populateReviews(userId);
setupReviewScrollObserver(userId);
}
const platform = {
mobile: data.active_on_discord_mobile,
@ -495,7 +670,7 @@ async function updatePresence(data) {
});
const activityList = document.querySelector(".activities");
const activitiesTitle = document.querySelector(".activity-header");
const activitiesTitle = document.querySelector(".activity-block-header");
if (activityList && activitiesTitle) {
if (filtered?.length) {
@ -509,9 +684,9 @@ async function updatePresence(data) {
getAllNoAsset();
}
if (data.kv?.snow === "true") loadEffectScript("snow");
if (data.kv?.rain === "true") loadEffectScript("rain");
if (data.kv?.stars === "true") loadEffectScript("stars");
if (kv.snow === "true") loadEffectScript("snow");
if (kv.rain === "true") loadEffectScript("rain");
if (kv.stars === "true") loadEffectScript("stars");
const loadingOverlay = document.getElementById("loading-overlay");
if (loadingOverlay) {
@ -637,6 +812,19 @@ if (userId && instanceUri) {
socket.addEventListener("message", (event) => {
const payload = JSON.parse(event.data);
if (payload.error || payload.success === false) {
const loadingOverlay = document.getElementById("loading-overlay");
if (loadingOverlay) {
loadingOverlay.innerHTML = `
<div class="error-message">
<p>${payload.error?.message || "An unknown error occurred."}</p>
</div>
`;
loadingOverlay.style.opacity = "1";
}
return;
}
if (payload.op === 1 && payload.d?.heartbeat_interval) {
heartbeatInterval = setInterval(() => {
socket.send(JSON.stringify({ op: 3 }));
@ -653,8 +841,8 @@ if (userId && instanceUri) {
}
if (payload.t === "INIT_STATE" || payload.t === "PRESENCE_UPDATE") {
updatePresence(payload.d);
requestAnimationFrame(() => updateElapsedAndProgress());
updatePresence(payload);
requestAnimationFrame(updateElapsedAndProgress);
}
});

View file

@ -25,24 +25,29 @@ const getRaindropColor = () => {
const createRaindrop = () => {
if (raindrops.length >= maxRaindrops) {
const oldestRaindrop = raindrops.shift();
rainContainer.removeChild(oldestRaindrop);
const oldest = raindrops.shift();
rainContainer.removeChild(oldest);
}
const raindrop = document.createElement("div");
raindrop.classList.add("raindrop");
raindrop.style.position = "absolute";
const height = Math.random() * 10 + 10;
raindrop.style.width = "2px";
raindrop.style.height = `${Math.random() * 10 + 10}px`;
raindrop.style.height = `${height}px`;
raindrop.style.background = getRaindropColor();
raindrop.style.borderRadius = "1px";
raindrop.style.left = `${Math.random() * window.innerWidth}px`;
raindrop.style.top = `-${raindrop.style.height}`;
raindrop.style.opacity = Math.random() * 0.5 + 0.3;
raindrop.x = Math.random() * window.innerWidth;
raindrop.y = -height;
raindrop.speed = Math.random() * 6 + 4;
raindrop.directionX = (Math.random() - 0.5) * 0.2;
raindrop.directionY = Math.random() * 0.5 + 0.8;
raindrop.style.left = `${raindrop.x}px`;
raindrop.style.top = `${raindrop.y}px`;
raindrops.push(raindrop);
rainContainer.appendChild(raindrop);
};
@ -51,23 +56,29 @@ setInterval(createRaindrop, 50);
function updateRaindrops() {
raindrops.forEach((raindrop, index) => {
const rect = raindrop.getBoundingClientRect();
const height = Number.parseFloat(raindrop.style.height);
raindrop.style.left = `${rect.left + raindrop.directionX * raindrop.speed}px`;
raindrop.style.top = `${rect.top + raindrop.directionY * raindrop.speed}px`;
raindrop.x += raindrop.directionX * raindrop.speed;
raindrop.y += raindrop.directionY * raindrop.speed;
if (rect.top + rect.height >= window.innerHeight) {
raindrop.style.left = `${raindrop.x}px`;
raindrop.style.top = `${raindrop.y}px`;
if (raindrop.y > window.innerHeight) {
rainContainer.removeChild(raindrop);
raindrops.splice(index, 1);
return;
}
if (
rect.left > window.innerWidth ||
rect.top > window.innerHeight ||
rect.left < 0
raindrop.x > window.innerWidth ||
raindrop.y > window.innerHeight ||
raindrop.x < 0
) {
raindrop.style.left = `${Math.random() * window.innerWidth}px`;
raindrop.style.top = `-${raindrop.style.height}`;
raindrop.x = Math.random() * window.innerWidth;
raindrop.y = -height;
raindrop.style.left = `${raindrop.x}px`;
raindrop.style.top = `${raindrop.y}px`;
}
});

View file

@ -25,17 +25,22 @@ const createSnowflake = () => {
const snowflake = document.createElement("div");
snowflake.classList.add("snowflake");
snowflake.style.position = "absolute";
snowflake.style.width = `${Math.random() * 3 + 2}px`;
snowflake.style.height = snowflake.style.width;
const size = Math.random() * 3 + 2;
snowflake.style.width = `${size}px`;
snowflake.style.height = `${size}px`;
snowflake.style.background = "white";
snowflake.style.borderRadius = "50%";
snowflake.style.opacity = Math.random();
snowflake.style.left = `${Math.random() * window.innerWidth}px`;
snowflake.style.top = `-${snowflake.style.height}`;
snowflake.x = Math.random() * window.innerWidth;
snowflake.y = -size;
snowflake.speed = Math.random() * 3 + 2;
snowflake.directionX = (Math.random() - 0.5) * 0.5;
snowflake.directionY = Math.random() * 0.5 + 0.5;
snowflake.style.left = `${snowflake.x}px`;
snowflake.style.top = `${snowflake.y}px`;
snowflakes.push(snowflake);
snowContainer.appendChild(snowflake);
};
@ -44,10 +49,12 @@ setInterval(createSnowflake, 80);
function updateSnowflakes() {
snowflakes.forEach((snowflake, index) => {
const rect = snowflake.getBoundingClientRect();
const size = Number.parseFloat(snowflake.style.width);
const centerX = snowflake.x + size / 2;
const centerY = snowflake.y + size / 2;
const dx = rect.left + rect.width / 2 - mouse.x;
const dy = rect.top + rect.height / 2 - mouse.y;
const dx = centerX - mouse.x;
const dy = centerY - mouse.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 30) {
@ -58,21 +65,27 @@ function updateSnowflakes() {
snowflake.directionY += (Math.random() - 0.5) * 0.01;
}
snowflake.style.left = `${rect.left + snowflake.directionX * snowflake.speed}px`;
snowflake.style.top = `${rect.top + snowflake.directionY * snowflake.speed}px`;
snowflake.x += snowflake.directionX * snowflake.speed;
snowflake.y += snowflake.directionY * snowflake.speed;
if (rect.top + rect.height >= window.innerHeight) {
snowflake.style.left = `${snowflake.x}px`;
snowflake.style.top = `${snowflake.y}px`;
if (snowflake.y > window.innerHeight) {
snowContainer.removeChild(snowflake);
snowflakes.splice(index, 1);
return;
}
if (
rect.left > window.innerWidth ||
rect.top > window.innerHeight ||
rect.left < 0
snowflake.x > window.innerWidth ||
snowflake.y > window.innerHeight ||
snowflake.x < 0
) {
snowflake.style.left = `${Math.random() * window.innerWidth}px`;
snowflake.style.top = `-${snowflake.style.height}`;
snowflake.x = Math.random() * window.innerWidth;
snowflake.y = -size;
snowflake.style.left = `${snowflake.x}px`;
snowflake.style.top = `${snowflake.y}px`;
}
});

View file

@ -11,48 +11,46 @@ document.body.appendChild(container);
for (let i = 0; i < 60; i++) {
const star = document.createElement("div");
star.className = "star";
const size = Math.random() * 2 + 1;
star.style.position = "absolute";
star.style.width = `${size}px`;
star.style.height = `${size}px`;
star.style.background = "white";
star.style.borderRadius = "50%";
star.style.opacity = Math.random();
star.style.top = `${Math.random() * 100}vh`;
star.style.left = `${Math.random() * 100}vw`;
star.style.animation = `twinkle ${Math.random() * 3 + 2}s infinite alternate ease-in-out`;
star.style.animationDuration = `${Math.random() * 3 + 2}s`;
container.appendChild(star);
}
function createShootingStar() {
const star = document.createElement("div");
star.classList.add("shooting-star");
star.className = "shooting-star";
let x = Math.random() * window.innerWidth * 0.8;
let y = Math.random() * window.innerHeight * 0.3;
star.x = Math.random() * window.innerWidth * 0.8;
star.y = Math.random() * window.innerHeight * 0.3;
const angle = (Math.random() * Math.PI) / 6 + Math.PI / 8;
const speed = 10;
const totalFrames = 60;
let frame = 0;
const deg = angle * (180 / Math.PI);
star.style.left = `${x}px`;
star.style.top = `${y}px`;
star.style.left = `${star.x}px`;
star.style.top = `${star.y}px`;
star.style.transform = `rotate(${deg}deg)`;
container.appendChild(star);
let frame = 0;
function animate() {
x += Math.cos(angle) * speed;
y += Math.sin(angle) * speed;
star.style.left = `${x}px`;
star.style.top = `${y}px`;
star.x += Math.cos(angle) * speed;
star.y += Math.sin(angle) * speed;
star.style.left = `${star.x}px`;
star.style.top = `${star.y}px`;
star.style.opacity = `${1 - frame / totalFrames}`;
frame++;
if (frame < totalFrames) {
requestAnimationFrame(animate);
} else {
} else if (star.parentNode === container) {
container.removeChild(star);
}
}

View file

@ -1,7 +1,9 @@
import { serverHandler } from "@/server";
import { verifyRequiredVariables } from "@config/environment";
import { logger } from "@creations.works/logger";
async function main(): Promise<void> {
verifyRequiredVariables();
serverHandler.initialize();
}

View file

@ -1,5 +1,10 @@
import { resolve } from "node:path";
import { badgeApi, lanyardConfig } from "@config/environment";
import {
badgeApi,
lanyardConfig,
plausibleScript,
reviewDb,
} from "@config/environment";
import { file } from "bun";
const routeDef: RouteDef = {
@ -23,6 +28,14 @@ async function handler(request: ExtendedRequest): Promise<Response> {
head.setAttribute("data-user-id", id || lanyardConfig.userId);
head.setAttribute("data-instance-uri", instance);
head.setAttribute("data-badge-url", badgeApi || "");
if (reviewDb.enabled) {
head.setAttribute("data-review-db", reviewDb.url);
}
if (plausibleScript) {
head.append(plausibleScript, { html: true });
}
},
})
.transform(await bunFile.text());

View file

@ -1,5 +1,5 @@
import { resolve } from "node:path";
import { environment } from "@config/environment";
import { environment, robotstxtPath } from "@config/environment";
import { logger } from "@creations.works/logger";
import {
type BunFile,
@ -65,10 +65,15 @@ class ServerHandler {
}
}
private async serveStaticFile(pathname: string): Promise<Response> {
try {
let filePath: string;
private async serveStaticFile(
request: ExtendedRequest,
pathname: string,
ip: string,
): Promise<Response> {
let filePath: string;
let response: Response;
try {
if (pathname === "/favicon.ico") {
filePath = resolve("public", "assets", "favicon.ico");
} else {
@ -81,16 +86,37 @@ class ServerHandler {
const fileContent: ArrayBuffer = await file.arrayBuffer();
const contentType: string = file.type || "application/octet-stream";
return new Response(fileContent, {
response = new Response(fileContent, {
headers: { "Content-Type": contentType },
});
} else {
logger.warn(`File not found: ${filePath}`);
response = new Response("Not Found", { status: 404 });
}
logger.warn(`File not found: ${filePath}`);
return new Response("Not Found", { status: 404 });
} catch (error) {
logger.error([`Error serving static file: ${pathname}`, error as Error]);
return new Response("Internal Server Error", { status: 500 });
response = new Response("Internal Server Error", { status: 500 });
}
this.logRequest(request, response, ip);
return response;
}
private logRequest(
request: ExtendedRequest,
response: Response,
ip: string | undefined,
): void {
logger.custom(
`[${request.method}]`,
`(${response.status})`,
[
request.url,
`${(performance.now() - request.startPerf).toFixed(2)}ms`,
ip || "unknown",
],
"90",
);
}
private async handleRequest(
@ -100,16 +126,52 @@ class ServerHandler {
const extendedRequest: ExtendedRequest = request as ExtendedRequest;
extendedRequest.startPerf = performance.now();
const headers = request.headers;
let ip = server.requestIP(request)?.address;
let response: Response;
if (!ip || ip.startsWith("172.") || ip === "127.0.0.1") {
ip =
headers.get("CF-Connecting-IP")?.trim() ||
headers.get("X-Real-IP")?.trim() ||
headers.get("X-Forwarded-For")?.split(",")[0].trim() ||
"unknown";
}
const pathname: string = new URL(request.url).pathname;
if (pathname === "/robots.txt" && robotstxtPath) {
try {
const file: BunFile = Bun.file(robotstxtPath);
if (await file.exists()) {
const fileContent: ArrayBuffer = await file.arrayBuffer();
const contentType: string = file.type || "text/plain";
response = new Response(fileContent, {
headers: { "Content-Type": contentType },
});
} else {
logger.warn(`File not found: ${robotstxtPath}`);
response = new Response("Not Found", { status: 404 });
}
} catch (error) {
logger.error([
`Error serving robots.txt: ${robotstxtPath}`,
error as Error,
]);
response = new Response("Internal Server Error", { status: 500 });
}
this.logRequest(extendedRequest, response, ip);
return response;
}
if (pathname.startsWith("/public") || pathname === "/favicon.ico") {
return await this.serveStaticFile(pathname);
return await this.serveStaticFile(extendedRequest, pathname, ip);
}
const match: MatchedRoute | null = this.router.match(request);
let requestBody: unknown = {};
let response: Response;
let logRequest = true;
if (match) {
const { filePath, params, query } = match;
@ -121,8 +183,6 @@ class ServerHandler {
? contentType.split(";")[0].trim()
: null;
logRequest = routeModule.routeDef.log !== false;
if (
routeModule.routeDef.needsBody === "json" &&
actualContentType === "application/json"
@ -231,30 +291,6 @@ class ServerHandler {
);
}
if (logRequest) {
const headers = request.headers;
let ip = server.requestIP(request)?.address;
if (!ip || ip.startsWith("172.") || ip === "127.0.0.1") {
ip =
headers.get("CF-Connecting-IP")?.trim() ||
headers.get("X-Real-IP")?.trim() ||
headers.get("X-Forwarded-For")?.split(",")[0].trim() ||
"unknown";
}
logger.custom(
`[${request.method}]`,
`(${response.status})`,
[
request.url,
`${(performance.now() - extendedRequest.startPerf).toFixed(2)}ms`,
ip || "unknown",
],
"90",
);
}
return response;
}
}

View file

@ -3,57 +3,72 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="View real-time Discord presence, activities, and badges with open-source integration." />
<meta name="color-scheme" content="dark" />
<title>Discord Presence</title>
<link rel="icon" id="site-icon" type="image/png" href="/public/assets/favicon.png" />
<link rel="stylesheet" href="/public/css/index.css" />
<link rel="stylesheet" href="/public/css/root.css" />
<meta name="color-scheme" content="dark" />
<link rel="icon" id="site-icon" type="image/png" />
</head>
<body>
<div id="loading-overlay">
<div id="loading-overlay" role="status" aria-live="polite">
<div class="loading-spinner"></div>
</div>
<a
href="https://git.creations.works/creations/profilePage"
target="_blank"
rel="noopener noreferrer"
>
<img
class="open-source-logo"
src="/public/assets/forgejo_logo.svg"
alt="Forgejo Logo"
style="opacity: 0.5"
/>
</a>
<header>
<a
href="https://git.creations.works/creations/profilePage"
target="_blank"
rel="noopener noreferrer"
title="View source code on Forgejo"
>
<img
class="open-source-logo"
src="/public/assets/forgejo_logo.svg"
alt="Forgejo open-source logo"
style="opacity: 0.5"
loading="lazy"
/>
</a>
</header>
<div class="user-card">
<div class="avatar-status-wrapper">
<div class="avatar-wrapper">
<img class="avatar hidden" src="" />
<div class="status-indicator offline hidden"></div>
</div>
<div class="user-info">
<div class="user-info-inner">
<h1 class="username"></h1>
<main>
<section class="user-card">
<div class="avatar-status-wrapper">
<div class="avatar-wrapper">
<img class="avatar hidden"/>
<img class="decoration hidden"/>
<div class="status-indicator offline hidden"></div>
</div>
<div class="user-info">
<div class="user-info-inner">
<h1 class="username"></h1>
</div>
</div>
</div>
</div>
</div>
</section>
<div id="badges" class="badges hidden"></div>
<section id="badges" class="badges hidden" aria-label="User Badges"></section>
<h2 class="activity-header hidden">Activities</h2>
<ul class="activities"></ul>
<section aria-label="Discord Activities" class="activities-section">
<h2 class="activity-block-header hidden">Activities</h2>
<ul class="activities"></ul>
</section>
<section class="readme hidden">
<div class="markdown-body"></div>
<section class="readme hidden" aria-label="Profile README">
<div class="markdown-body"></div>
</section>
</main>
<section class="reviews hidden" aria-label="User Reviews">
<h2>User Reviews</h2>
<ul class="reviews-list">
</ul>
</section>
<script src="/public/js/index.js"></script>
<script src="/public/js/index.js" type="module"></script>
</body>
</html>