Skip to content

Commit

Permalink
Merge pull request #1 from sant0s12/ndk
Browse files Browse the repository at this point in the history
Switch to NDK
  • Loading branch information
sant0s12 committed Mar 2, 2024
2 parents 9127eb2 + 2b54510 commit 3be8fb6
Show file tree
Hide file tree
Showing 12 changed files with 541 additions and 280 deletions.
380 changes: 375 additions & 5 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
},
"type": "module",
"dependencies": {
"@nostr-dev-kit/ndk": "^2.5.0",
"@nostr-dev-kit/ndk-svelte": "^2.2.7",
"dompurify": "^3.0.9",
"lodash-es": "^4.17.21",
"nostr-tools": "^2.1.7",
Expand Down
67 changes: 18 additions & 49 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,22 @@
import { browser } from '$app/environment';
import { persisted } from 'svelte-persisted-store';
import type { EventTemplate, VerifiedEvent } from 'nostr-tools';
import { get, writable } from 'svelte/store';
import { getUserMetadata, type User } from '$lib/nostr';
import { getUserRelays, setRandomRelay } from './relays';

declare global {
interface Window {
nostr: {
getPublicKey: () => Promise<string>;
signEvent: (event: EventTemplate) => Promise<VerifiedEvent>;
};
}
}

export async function loginWithExtension(retries: number = 10) {
if (browser && window.hasOwnProperty('nostr')) {
let pubkey = await window.nostr.getPublicKey();
if (!pubkey) {
throw new Error('Failed to get user pubkey');
}

let user = { pubkey };

let found = false;
for (let i = 0; i < retries; i++) {
if (await getUserRelays(user)) {
found = true;
break;
} else {
await setRandomRelay();
}
}

if (!found) {
throw new Error(`Failed to get user relays after ${retries} tries`);
}

loggedInUser.set(await getUserMetadata(user));
loggedInWithExtension.set(true);

console.log("Successfully logged in");

return get(loggedInUser);
} else {
throw new Error('No extension found');
}
import { get } from 'svelte/store';
import { ndk, signer } from '$lib/nostr';
import { NDKNip07Signer } from '@nostr-dev-kit/ndk';

export function loginWithExtension() {
signer.set(new NDKNip07Signer());
get(signer)
.user()
.then((user) => {
ndk.update(($ndk) => {
$ndk.signer = get(signer);
$ndk.activeUser = user;
$ndk.activeUser.ndk = $ndk;
$ndk.activeUser.fetchProfile().then(() => ndk.set(get(ndk)));
$ndk.connect();
return $ndk;
});
});
}

export const loggedInWithExtension = persisted('loggedInWithExtension', false);

export const loggedInUser = writable<User | null>(null);
67 changes: 32 additions & 35 deletions src/lib/components/PostHeader.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import { base } from '$app/paths';
import Avatar from '$lib/components/Avatar.svelte';
import { getUserMetadata, npubEncodeShort, type Community, type Post } from '$lib/nostr';
import { npubEncodeShort, type Community, type Post, ndk } from '$lib/nostr';
import DOMPurify from 'dompurify';
import { ArrowsRepeatOutline, BadgeCheckSolid } from 'flowbite-svelte-icons';
import { onMount } from 'svelte';
Expand All @@ -15,8 +15,8 @@
$: {
for (const community of communities) {
community.name = DOMPurify.sanitize(community.name, {ALLOWED_TAGS: []});
community.id = DOMPurify.sanitize(community.id, {ALLOWED_TAGS: []});
community.name = DOMPurify.sanitize(community.name, { ALLOWED_TAGS: [] });
community.id = DOMPurify.sanitize(community.id, { ALLOWED_TAGS: [] });
communityLinks.push(
`<a href="${base}/c/${community.id}" class="hover:underline"> <p>${community.name}</p> </a>`
Expand All @@ -28,12 +28,7 @@
joinedLinks = communityLinks.join('<span class="text-gray-400"> • </span>');
}
// Get the user metadata
onMount(async () => {
if (!post.author.meta) {
post.author = await getUserMetadata(post.author);
}
});
$: post.author.fetchProfile();
// Await the communities
onMount(async () => {
Expand Down Expand Up @@ -65,7 +60,7 @@
</div>
{:else}
<a href="{base}/p/{post.author.pubkey}">
<Avatar src={post.author.picture} fallback={post.author.name} size={'xs'} />
<Avatar src={post.author.profile?.image} fallback={post.author.profile?.name} size={'xs'} />
</a>
{/if}
<div class="flex flex-col text-xs justify-center items-start">
Expand All @@ -78,45 +73,47 @@
href="{base}/p/{post.author.pubkey}"
class="inline-flex space-x-1 items-center hover:underline"
>
{#if post.author.name}
<p>{post.author.name}</p>
{#if post.author.profile?.name}
<p>{post.author.profile.name}</p>
{:else}
<p>{npubEncodeShort(post.author.pubkey)}</p>
{/if}
{#if post.author.verified}
<!-- {#if post.author.verified}
<BadgeCheckSolid size="xs" />
<div>
{post.author.nip05}
</div>
{/if}
{/if} -->
</a>
</div>
</div>
{#if post.repostedBy}
{#each post.repostedBy as repostedBy}
{#await repostedBy then repostedBy}
{#await getUserMetadata(repostedBy.author) then repostAuthor}
<div class="flex flex-row overflow-hidden space-x-2 items-center">
<ArrowsRepeatOutline size="xs" />
<div class="flex flex-col text-xs justify-center items-start">
<a
href="{base}/p/{repostAuthor.pubkey}"
class="inline-flex space-x-1 items-center hover:underline"
>
{#if repostAuthor.name}
<p>{repostAuthor.name}</p>
{:else}
<p>{npubEncodeShort(repostAuthor.pubkey)}</p>
{/if}
{#if repostAuthor.verified}
<BadgeCheckSolid size="xs" />
<div>
{repostAuthor.nip05}
</div>
{/if}
</a>
{#await repostedBy.author.fetchProfile() then repostAuthor}
{#if repostAuthor}
<div class="flex flex-row overflow-hidden space-x-2 items-center">
<ArrowsRepeatOutline size="xs" />
<div class="flex flex-col text-xs justify-center items-start">
<a
href="{base}/p/{repostAuthor.pubkey}"
class="inline-flex space-x-1 items-center hover:underline"
>
{#if repostAuthor.name}
<p>{repostAuthor.name}</p>
{:else if repostAuthor.pubkey}
<p>{npubEncodeShort(repostAuthor.pubkey)}</p>
{/if}
{#if repostAuthor.verified}
<BadgeCheckSolid size="xs" />
<div>
{repostAuthor.nip05}
</div>
{/if}
</a>
</div>
</div>
</div>
{/if}
{/await}
{/await}
{/each}
Expand Down
26 changes: 10 additions & 16 deletions src/lib/components/PostInteraction.svelte
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<script lang="ts">
import { base } from '$app/paths';
import { loggedInUser } from '$lib/auth';
import { getPostReactions, type Post } from '$lib/nostr';
import { relayPool, writeRelays } from '$lib/relays';
import { getPostReactions, ndk, type Post } from '$lib/nostr';
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { Button, ButtonGroup } from 'flowbite-svelte';
import { ChevronDownOutline, ChevronUpOutline, MessageDotsSolid } from 'flowbite-svelte-icons';
import { kinds, type UnsignedEvent } from 'nostr-tools';
Expand All @@ -23,9 +22,9 @@
});
async function getUserVote() {
if ($loggedInUser) {
let event = await relayPool.get($writeRelays, {
authors: [$loggedInUser.pubkey],
if ($ndk.activeUser) {
let event = await $ndk.fetchEvent({
authors: [$ndk.activeUser.pubkey],
kinds: [kinds.Reaction],
'#e': [post.id],
'#p': [post.author.pubkey]
Expand All @@ -44,27 +43,22 @@
}
async function vote(vote: number) {
if (userVote == vote || !$loggedInUser) {
if (userVote == vote || !$ndk.activeUser) {
return;
}
let reactionEvent: UnsignedEvent = {
let reactionEvent = new NDKEvent($ndk, {
kind: kinds.Reaction,
pubkey: $loggedInUser.pubkey,
pubkey: $ndk.activeUser.pubkey,
created_at: Math.round(new Date().getTime() / 1000),
content: vote == 1 ? '+' : '-',
tags: [
['e', post.id],
['p', post.author.pubkey]
]
};
});
let signedEvent = await window.nostr.signEvent(reactionEvent);
if (signedEvent) {
await Promise.any(relayPool.publish($writeRelays, signedEvent));
} else {
console.error('Failed to sign event');
}
await reactionEvent.publish();
userVote = await getUserVote();
if (vote == 1) {
Expand Down
Loading

0 comments on commit 3be8fb6

Please sign in to comment.