Mirror of @tangled.org/core. Running on a Raspberry Pi Zero 2 (Please be gentle).
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

avatar: generate a random color for users without a pfp

Signed-off-by: Anirudh Oppiliappan <anirudh@tangled.sh>

+33 -4
+33 -4
avatar/src/index.js
··· 1 1 export default { 2 2 async fetch(request, env) { 3 + // Helper function to generate a color from a string 4 + const stringToColor = (str) => { 5 + let hash = 0; 6 + for (let i = 0; i < str.length; i++) { 7 + hash = str.charCodeAt(i) + ((hash << 5) - hash); 8 + } 9 + let color = "#"; 10 + for (let i = 0; i < 3; i++) { 11 + const value = (hash >> (i * 8)) & 0xff; 12 + color += ("00" + value.toString(16)).substr(-2); 13 + } 14 + return color; 15 + }; 16 + 3 17 const url = new URL(request.url); 4 18 const { pathname, searchParams } = url; 5 19 ··· 74 60 const profile = await profileResponse.json(); 75 61 const avatar = profile.avatar; 76 62 77 - if (!avatar) { 78 - return new Response(`avatar not found for ${actor}.`, { status: 404 }); 63 + let avatarUrl = profile.avatar; 64 + 65 + if (!avatarUrl) { 66 + // Generate a random color based on the actor string 67 + const bgColor = stringToColor(actor); 68 + const size = resizeToTiny ? 32 : 128; 69 + const svg = `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg"><rect width="${size}" height="${size}" fill="${bgColor}"/></svg>`; 70 + const svgData = new TextEncoder().encode(svg); 71 + 72 + response = new Response(svgData, { 73 + headers: { 74 + "Content-Type": "image/svg+xml", 75 + "Cache-Control": "public, max-age=43200", 76 + }, 77 + }); 78 + await cache.put(cacheKey, response.clone()); 79 + return response; 79 80 } 80 81 81 82 // Resize if requested 82 83 let avatarResponse; 83 84 if (resizeToTiny) { 84 - avatarResponse = await fetch(avatar, { 85 + avatarResponse = await fetch(avatarUrl, { 85 86 cf: { 86 87 image: { 87 88 width: 32, ··· 107 78 }, 108 79 }); 109 80 } else { 110 - avatarResponse = await fetch(avatar); 81 + avatarResponse = await fetch(avatarUrl); 111 82 } 112 83 113 84 if (!avatarResponse.ok) {