Skip to content

feat: added compression to images #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"helmet": "^8.1.0",
"jose": "^6.0.10",
"ts-mixer": "^6.0.4",
"undici": "^7.12.0",
"viem": "^2.29.3"
},
"type": "module",
Expand Down
17 changes: 16 additions & 1 deletion scripts/_init.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,25 @@ require('dotenv').config({ path: path.resolve(__dirname, '../.env') });

const admin = require('firebase-admin');

process.env.FIRESTORE_EMULATOR_HOST ??= 'localhost:8080';
const { setGlobalDispatcher, Agent } = require('undici');

setGlobalDispatcher(new Agent({
keepAliveTimeout: 60_000,
keepAliveMaxTimeout: 60_000,
connect: {
family: 4,
},
}));

// process.env.FIRESTORE_EMULATOR_HOST ??= 'localhost:8080';

function cleanKey(k) { return k ? k.replace(/\\n/g, '\n') : undefined; }

process.env.PINATA_JWT ??= process.env.API_PINATA_JWT;
process.env.PINATA_API_KEY ??= process.env.API_PINATA_API_KEY;
process.env.PINATA_SECRET_API_KEY ??= process.env.API_PINATA_SECRET_API_KEY;
process.env.IPFS_GATEWAY_BASE ??= 'https://cloudflare-ipfs.com/ipfs';

const {
API_FIREBASE_TYPE,
API_FIREBASE_PROJECT_ID,
Expand Down
19 changes: 17 additions & 2 deletions src/datasources/users/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,25 @@ export class UsersCommands extends DataSourceManager {
if (!current) throw new Error(`User ${address} not found`);

const cleanPatch = stripNulls(patch);
const merged = { ...current, ...cleanPatch };
const nextDoc: Partial<FirestoreUser> = { ...cleanPatch };

if (typeof cleanPatch.profilePicture === 'string'
&& cleanPatch.profilePicture
&& cleanPatch.profilePicture !== current.profilePicture) {
nextDoc.profilePictureOriginal = cleanPatch.profilePicture;
}

if (typeof cleanPatch.coverPicture === 'string'
&& cleanPatch.coverPicture
&& cleanPatch.coverPicture !== current.coverPicture) {
nextDoc.coverPictureOriginal = cleanPatch.coverPicture;
}

const merged = { ...current, ...nextDoc };
console.log('merged user data:', merged);
const keywords = buildKeywords(merged, USER_PREFIX_FIELDS, USER_WHOLE_FIELDS);
const timestamp = Date.now();
const updateDoc = {...cleanPatch, keywords, updatedAt: timestamp,};
const updateDoc = { ...nextDoc, keywords, updatedAt: timestamp };
const { keywords: _k, ...publicUser } = { ...merged, updatedAt: timestamp };

await dao.update(address, updateDoc);
Expand Down
87 changes: 82 additions & 5 deletions src/functions/flows/users/triggers.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,104 @@
import { onDocumentCreated, onDocumentUpdated } from 'firebase-functions/v2/firestore';
import { enhanceTrigger } from "../../manager";
import { FirestoreUser } from "../../../externals/firebase/types";
import { enhanceTrigger } from '../../manager';
import { FirestoreUser } from '../../../externals/firebase/types';
import { processImage } from '../../processors/image';
import { extractCid } from '../../processors/ipfs';

function shouldOptimize(current?: string | null, original?: string | null): boolean {
const cur = extractCid(current);
const org = extractCid(original);
if (!cur) return false;
if (!org) return true;
return cur === org;
}

async function buildUserPicturePatch(wallet: string, user: FirestoreUser) {
const patch: Partial<FirestoreUser> & Record<string, any> = {};
let changed = false;

if (shouldOptimize(user.profilePicture, user.profilePictureOriginal)) {
try {
const { optimizedUri, originalUri } = await processImage({
source: user.profilePicture,
preset: 'profile',
tag: `user-${wallet}-profile`,
mode: 'ipfs',
});
patch.profilePicture = optimizedUri;
patch.profilePictureOriginal = originalUri;
changed = true;
console.log(`🖼️ optimized profilePicture for ${wallet}`);
} catch (err) {
console.warn(`⚠️ optimizing profilePicture failed for ${wallet}:`, err);
}
}

if (shouldOptimize(user.coverPicture, user.coverPictureOriginal)) {
try {
const { optimizedUri, originalUri } = await processImage({
source: user.coverPicture,
preset: 'cover',
tag: `user-${wallet}-cover`,
mode: 'ipfs',
});
patch.coverPicture = optimizedUri;
patch.coverPictureOriginal = originalUri;
changed = true;
console.log(`🖼️ optimized coverPicture for ${wallet}`);
} catch (err) {
console.warn(`⚠️ optimizing coverPicture failed for ${wallet}:`, err);
}
}

return changed ? patch : null;
}

export const logUserCreated = onDocumentCreated(
'users/{wallet}',
enhanceTrigger(async ({ rank, activity }, event) => {
const { wallet } = event.params;
const newUser = event.data!.data() as FirestoreUser;
const snap = event.data!; // QueryDocumentSnapshot
const newUser = snap.data() as FirestoreUser;

console.log(`👤 New user ${wallet} created (email: ${newUser.email ?? 'n/a'})`);

await activity.userRegistered(wallet);
await rank.maybeRankUp(wallet);

console.log(`🎉 ${wallet} promoted to watcher & perks seeded`);
})

try {
const patch = await buildUserPicturePatch(wallet, newUser);
if (patch) {
patch.updatedAt = Date.now();
await snap.ref.update(patch);
console.log(`🖼️ processed user pictures for ${wallet}`);
}
} catch (err) {
console.warn(`⚠️ processUserPictures (create) failed for ${wallet}:`, err);
}
}),
);

export const logUserUpdated = onDocumentUpdated(
'users/{wallet}',
enhanceTrigger(async ({ activity }, event) => {
const { wallet } = event.params;
const change = event.data!; // Change<QueryDocumentSnapshot>
const after = change.after.data() as FirestoreUser | undefined;
if (!after) return;

await activity.userUpdated(wallet);
})

try {
const patch = await buildUserPicturePatch(wallet, after);
if (patch) {
patch.updatedAt = Date.now();
await change.after.ref.update(patch);
console.log(`🖼️ processed user pictures (update) for ${wallet}`);
}
} catch (err) {
console.warn(`⚠️ processUserPictures (update) failed for ${wallet}:`, err);
}
}),
);
1 change: 1 addition & 0 deletions src/functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"firebase-admin": "^13.3.0",
"firebase-functions": "^6.3.2",
"reflect-metadata": "^0.2.2",
"sharp": "^0.34.3",
"ts-mixer": "^6.0.4",
"viem": "^2.31.7"
},
Expand Down
59 changes: 59 additions & 0 deletions src/functions/processors/image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* processors/image.ts */
import sharp from 'sharp';
import { fetchImage, uploadBufferToIpfs, extractCid } from './ipfs';

type Preset = 'profile' | 'cover' | 'poster' | 'square' | 'wallpaper' | 'generic';

export interface ProcessOptions {
source: string;
preset: Preset;
tag?: string;
mode: 'ipfs' | 'http'; // ← NUEVO
}

function presetToResize(preset: Preset): sharp.ResizeOptions {
switch (preset) {
case 'profile': return { width: 256, height: 256, fit: 'cover' };
case 'cover': return { width: 1200, height: 400, fit: 'cover' };
case 'poster': return { width: 720, height: 1080, fit: 'cover' };
case 'square': return { width: 1024, height: 1024, fit: 'cover' };
case 'wallpaper': return { width: 1920, height: 1080, fit: 'cover' };
default: return { width: 1280, height: 720, fit: 'inside', withoutEnlargement: true };
}
}

export async function processImage({
source,
preset,
tag,
mode,
}: ProcessOptions): Promise<{
optimizedUri: string;
originalUri: string;
width: number;
height: number;
}> {
console.log(`[processImage] mode=${mode} preset=${preset} src=${source}`);

const { buffer: original, originalUri } = await fetchImage(source, mode);

const resizeCfg = presetToResize(preset);
const optimized = await sharp(original).rotate().resize(resizeCfg).webp({ quality: 82 }).toBuffer();

const meta = await sharp(optimized).metadata();
const w = meta.width || 0;
const h = meta.height || 0;

const pinMeta = tag ? { name: `opt-${tag}`, keyvalues: { preset } } : undefined;
const optimizedUri = await uploadBufferToIpfs(optimized, `optimized.webp`, 'image/webp', pinMeta);

return { optimizedUri, originalUri, width: w, height: h };
}

export function inferPresetFromTitle(title?: string | null): Preset {
const t = (title || '').toLowerCase();
if (t.includes('poster')) return 'poster';
if (t.includes('square')) return 'square';
if (t.includes('wallpaper')) return 'wallpaper';
return 'generic';
}
Loading