Skip to content
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
10 changes: 6 additions & 4 deletions src/components/AddToListDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,13 @@ export function AddToListDialog({
if (selectedLists.size === 0) return;

try {
const promises = Array.from(selectedLists).map(listId =>
const selectedListEntries = (userLists || []).filter((list) => selectedLists.has(list.id));
const promises = selectedListEntries.map((list) =>
addToList.mutateAsync({
listId,
videoCoordinate
})
listId: list.id,
ownerPubkey: list.pubkey,
videoCoordinate,
}),
);

await Promise.all(promises);
Expand Down
238 changes: 134 additions & 104 deletions src/hooks/useVideoLists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import type { NostrEvent, NostrFilter } from '@nostrify/nostrify';
import { SHORT_VIDEO_KIND } from '@/types/video';
import { resolveListPermissions } from '@/lib/listPermissions';

export type PlayOrder = 'chronological' | 'reverse' | 'manual' | 'shuffle';

Expand Down Expand Up @@ -45,13 +46,15 @@ function parseVideoList(event: NostrEvent): VideoList | null {
// Extract categorization tags (t tags)
const tags = event.tags
.filter(tag => tag[0] === 't')
.map(tag => tag[1]);
.map(tag => tag[1])
.filter((tag): tag is string => Boolean(tag));

// Extract collaborative settings
const isCollaborative = event.tags.find(tag => tag[0] === 'collaborative')?.[1] === 'true';
const allowedCollaborators = event.tags
.filter(tag => tag[0] === 'collaborator')
.map(tag => tag[1]);
.map(tag => tag[1])
.filter((pubkey): pubkey is string => Boolean(pubkey));

// Extract featured thumbnail
const thumbnailEventId = event.tags.find(tag => tag[0] === 'thumbnail-event')?.[1];
Expand Down Expand Up @@ -91,6 +94,96 @@ function parseVideoList(event: NostrEvent): VideoList | null {
};
}

function buildListTags(
list: Pick<VideoList, 'id' | 'name' | 'description' | 'image' | 'tags' | 'isCollaborative' | 'allowedCollaborators' | 'thumbnailEventId' | 'playOrder'>,
videoCoordinates: string[],
): string[][] {
const tags: string[][] = [
['d', list.id],
['title', list.name],
];

if (list.description) {
tags.push(['description', list.description]);
}

if (list.image) {
tags.push(['image', list.image]);
}

if (list.tags && list.tags.length > 0) {
list.tags.forEach((tag) => {
tags.push(['t', tag]);
});
}

if (list.isCollaborative) {
tags.push(['collaborative', 'true']);
if (list.allowedCollaborators && list.allowedCollaborators.length > 0) {
list.allowedCollaborators.forEach((pubkey) => {
tags.push(['collaborator', pubkey]);
});
}
}

if (list.thumbnailEventId) {
tags.push(['thumbnail-event', list.thumbnailEventId]);
}

if (list.playOrder && list.playOrder !== 'chronological') {
tags.push(['play-order', list.playOrder]);
}

videoCoordinates.forEach((coord) => {
tags.push(['a', coord]);
});

return tags;
}

async function fetchListByOwner(
nostr: { query: (filters: NostrFilter[], options: { signal: AbortSignal }) => Promise<NostrEvent[]> },
ownerPubkey: string,
listId: string,
signal: AbortSignal,
): Promise<VideoList> {
const ownerEvents = await nostr.query([{
kinds: [30005],
authors: [ownerPubkey],
'#d': [listId],
limit: 1,
}], { signal });

if (ownerEvents.length === 0) {
throw new Error('List not found');
}

const ownerList = parseVideoList(ownerEvents[0]);
if (!ownerList) {
throw new Error('Invalid list format');
}

if (!ownerList.isCollaborative || !ownerList.allowedCollaborators || ownerList.allowedCollaborators.length === 0) {
return ownerList;
}

const participantPubkeys = Array.from(new Set([ownerPubkey, ...ownerList.allowedCollaborators]));
const participantEvents = await nostr.query([{
kinds: [30005],
authors: participantPubkeys,
'#d': [listId],
limit: 50,
}], { signal });

const participantSet = new Set(participantPubkeys);
const latestList = participantEvents
.map(parseVideoList)
.filter((list): list is VideoList => list !== null && participantSet.has(list.pubkey))
.sort((a, b) => b.createdAt - a.createdAt)[0];

return latestList || ownerList;
}

/**
* Hook to fetch video lists
*/
Expand Down Expand Up @@ -299,72 +392,51 @@ export function useCreateVideoList() {
*/
export function useAddVideoToList() {
const { nostr } = useNostr();
const { mutate: publishEvent } = useNostrPublish();
const { mutateAsync: publishEvent } = useNostrPublish();
const queryClient = useQueryClient();
const { user } = useCurrentUser();

return useMutation({
mutationFn: async ({
listId,
ownerPubkey,
videoCoordinate
}: {
listId: string;
ownerPubkey: string;
videoCoordinate: string;
}) => {
if (!user) throw new Error('Must be logged in to modify lists');

// Fetch current list
const signal = AbortSignal.timeout(5000);
const events = await nostr.query([{
kinds: [30005],
authors: [user.pubkey],
'#d': [listId],
limit: 1
}], { signal });

if (events.length === 0) {
throw new Error('List not found');
const currentList = await fetchListByOwner(nostr, ownerPubkey, listId, signal);
const permissions = resolveListPermissions({
ownerPubkey,
isCollaborative: currentList.isCollaborative,
allowedCollaborators: currentList.allowedCollaborators,
}, user.pubkey);
if (!permissions.canEditContent) {
throw new Error('You do not have permission to edit this list');
}

const currentList = parseVideoList(events[0]);
if (!currentList) throw new Error('Invalid list format');

// Check if video already in list
if (currentList.videoCoordinates.includes(videoCoordinate)) {
return; // Already in list
}

// Rebuild tags with new video
const tags: string[][] = [
['d', listId],
['title', currentList.name]
];

if (currentList.description) {
tags.push(['description', currentList.description]);
}

if (currentList.image) {
tags.push(['image', currentList.image]);
}

// Add all existing videos
currentList.videoCoordinates.forEach(coord => {
tags.push(['a', coord]);
});

// Add new video
tags.push(['a', videoCoordinate]);
const tags = buildListTags(currentList, [...currentList.videoCoordinates, videoCoordinate]);

await publishEvent({
kind: 30005,
content: '',
tags
});
},
onSuccess: () => {
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ['video-lists'] });
queryClient.invalidateQueries({ queryKey: ['videos-in-lists'] });
queryClient.invalidateQueries({ queryKey: ['list-videos'] });
queryClient.invalidateQueries({ queryKey: ['list-detail', variables.ownerPubkey, variables.listId] });
}
});
}
Expand All @@ -374,97 +446,51 @@ export function useAddVideoToList() {
*/
export function useRemoveVideoFromList() {
const { nostr } = useNostr();
const { mutate: publishEvent } = useNostrPublish();
const { mutateAsync: publishEvent } = useNostrPublish();
const queryClient = useQueryClient();
const { user } = useCurrentUser();

return useMutation({
mutationFn: async ({
listId,
ownerPubkey,
videoCoordinate
}: {
listId: string;
ownerPubkey: string;
videoCoordinate: string;
}) => {
if (!user) throw new Error('Must be logged in to modify lists');

// Fetch current list
const signal = AbortSignal.timeout(5000);
const events = await nostr.query([{
kinds: [30005],
authors: [user.pubkey],
'#d': [listId],
limit: 1
}], { signal });

if (events.length === 0) {
throw new Error('List not found');
const currentList = await fetchListByOwner(nostr, ownerPubkey, listId, signal);
const permissions = resolveListPermissions({
ownerPubkey,
isCollaborative: currentList.isCollaborative,
allowedCollaborators: currentList.allowedCollaborators,
}, user.pubkey);
if (!permissions.canEditContent) {
throw new Error('You do not have permission to edit this list');
}

const currentList = parseVideoList(events[0]);
if (!currentList) throw new Error('Invalid list format');

// Filter out the video to remove
const updatedCoordinates = currentList.videoCoordinates.filter(
coord => coord !== videoCoordinate
);

// Rebuild tags without the removed video
const tags: string[][] = [
['d', listId],
['title', currentList.name]
];

if (currentList.description) {
tags.push(['description', currentList.description]);
}

if (currentList.image) {
tags.push(['image', currentList.image]);
}

// Add categorization tags
if (currentList.tags && currentList.tags.length > 0) {
currentList.tags.forEach(tag => {
tags.push(['t', tag]);
});
}

// Add collaborative settings
if (currentList.isCollaborative) {
tags.push(['collaborative', 'true']);
if (currentList.allowedCollaborators && currentList.allowedCollaborators.length > 0) {
currentList.allowedCollaborators.forEach(pubkey => {
tags.push(['collaborator', pubkey]);
});
}
}

// Add featured thumbnail
if (currentList.thumbnailEventId) {
tags.push(['thumbnail-event', currentList.thumbnailEventId]);
}

// Add play order
if (currentList.playOrder && currentList.playOrder !== 'chronological') {
tags.push(['play-order', currentList.playOrder]);
}

// Add remaining videos
updatedCoordinates.forEach(coord => {
tags.push(['a', coord]);
});
const tags = buildListTags(currentList, updatedCoordinates);

await publishEvent({
kind: 30005,
content: '',
tags
});
},
onSuccess: () => {
onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ['video-lists'] });
queryClient.invalidateQueries({ queryKey: ['videos-in-lists'] });
queryClient.invalidateQueries({ queryKey: ['list-videos'] });
queryClient.invalidateQueries({ queryKey: ['list-detail', variables.ownerPubkey, variables.listId] });
}
});
}
Expand Down Expand Up @@ -518,30 +544,34 @@ export function useDeleteVideoList() {
const { user } = useCurrentUser();

return useMutation({
mutationFn: async ({ listId }: { listId: string }) => {
mutationFn: async ({ listId, ownerPubkey }: { listId: string; ownerPubkey: string }) => {
if (!user) throw new Error('Must be logged in to delete lists');
if (user.pubkey !== ownerPubkey) {
throw new Error('Only the list owner can delete this list');
}

// Publish a kind 5 deletion event targeting the list
// The 'a' tag references the addressable event to delete
await publishEvent({
kind: 5, // NIP-09 deletion event
content: 'List deleted by owner',
tags: [
['a', `30005:${user.pubkey}:${listId}`],
['a', `30005:${ownerPubkey}:${listId}`],
]
});

return { listId };
return { listId, ownerPubkey };
},
onSuccess: ({ listId }) => {
onSuccess: ({ listId, ownerPubkey }) => {
// Remove from cache immediately
if (user) {
if (user && user.pubkey === ownerPubkey) {
queryClient.setQueryData<VideoList[]>(
['video-lists', user.pubkey],
['video-lists', ownerPubkey],
(oldLists) => oldLists?.filter(l => l.id !== listId) || []
);
}
queryClient.invalidateQueries({ queryKey: ['video-lists'] });
queryClient.invalidateQueries({ queryKey: ['list-detail', ownerPubkey, listId] });
queryClient.invalidateQueries({ queryKey: ['trending-video-lists'] });
queryClient.invalidateQueries({ queryKey: ['followed-users-lists'] });
}
Expand Down
Loading
Loading