40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
'use client';
|
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
|
import { useAuth } from '@/components/id/auth-provider';
|
|
import { apiFetch } from '@/lib/api';
|
|
|
|
interface AvatarAccessResponse {
|
|
accessUrl: string;
|
|
expiresAt: string;
|
|
}
|
|
|
|
export function useAvatarUrl(userId: string | undefined, hasAvatar: boolean | undefined, token: string | null) {
|
|
const { isPinLocked } = useAuth();
|
|
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
|
|
|
const refresh = useCallback(async () => {
|
|
if (!userId || !token || !hasAvatar || isPinLocked) {
|
|
setAvatarUrl(null);
|
|
return;
|
|
}
|
|
try {
|
|
const response = await apiFetch<AvatarAccessResponse>(`/media/avatars/${userId}/url`, {}, token);
|
|
setAvatarUrl(response.accessUrl);
|
|
} catch {
|
|
setAvatarUrl(null);
|
|
}
|
|
}, [hasAvatar, isPinLocked, token, userId]);
|
|
|
|
useEffect(() => {
|
|
void refresh();
|
|
if (!hasAvatar) return;
|
|
const timer = window.setInterval(() => {
|
|
void refresh();
|
|
}, 14 * 60 * 1000);
|
|
return () => window.clearInterval(timer);
|
|
}, [hasAvatar, refresh]);
|
|
|
|
return { avatarUrl, refreshAvatarUrl: refresh };
|
|
}
|