plebdevs/src/hooks/nostrQueries/content/useVideosQuery.js

57 lines
2.0 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNDKContext } from '@/context/NDKContext';
2024-08-09 14:28:57 -05:00
import axios from 'axios';
2024-09-17 13:55:51 -05:00
import appConfig from '@/config/appConfig';
2024-09-15 13:27:37 -05:00
export function useVideosQuery() {
const [isClient, setIsClient] = useState(false);
const {ndk, addSigner} = useNDKContext();
useEffect(() => {
setIsClient(true);
}, []);
2024-08-09 14:28:57 -05:00
const hasRequiredProperties = (event, contentIds) => {
2024-09-15 13:27:37 -05:00
const hasVideo = event.tags.some(([tag, value]) => tag === "t" && value === "video");
2024-08-09 14:28:57 -05:00
const hasId = event.tags.some(([tag, value]) => tag === "d" && contentIds.includes(value));
2024-09-15 13:27:37 -05:00
return hasVideo && hasId;
2024-08-08 16:29:16 -05:00
};
2024-09-15 13:27:37 -05:00
const fetchVideosFromNDK = async () => {
2024-08-08 16:29:16 -05:00
try {
2024-08-09 14:28:57 -05:00
const response = await axios.get(`/api/content/all`);
const contentIds = response.data;
if (!contentIds || contentIds.length === 0) {
return []; // Return early if no content IDs are found
2024-08-08 16:29:16 -05:00
}
2024-08-09 14:28:57 -05:00
2024-08-08 16:29:16 -05:00
await ndk.connect();
2024-09-17 13:55:51 -05:00
const filter = { kinds: [30023, 30402], authors: appConfig.authorPubkeys };
2024-08-08 16:29:16 -05:00
const events = await ndk.fetchEvents(filter);
if (events && events.size > 0) {
const eventsArray = Array.from(events);
2024-09-15 13:27:37 -05:00
const videos = eventsArray.filter(event => hasRequiredProperties(event, contentIds));
return videos;
2024-08-08 16:29:16 -05:00
}
return [];
} catch (error) {
2024-09-15 13:27:37 -05:00
console.error('Error fetching videos from NDK:', error);
2024-08-08 16:29:16 -05:00
return [];
}
};
2024-09-15 13:27:37 -05:00
const { data: videos, isLoading: videosLoading, error: videosError, refetch: refetchVideos } = useQuery({
queryKey: ['videos', isClient],
queryFn: fetchVideosFromNDK,
2024-08-09 14:28:57 -05:00
// staleTime: 1000 * 60 * 30, // 30 minutes
// refetchInterval: 1000 * 60 * 30, // 30 minutes
2024-08-08 16:29:16 -05:00
enabled: isClient,
});
2024-09-15 13:27:37 -05:00
return { videos, videosLoading, videosError, refetchVideos };
2024-08-08 16:29:16 -05:00
}