Compare commits

...

4 Commits

Author SHA1 Message Date
Bojan Mojsilovic a69f7d5950 Proper subs from profile and article 2024-06-10 15:44:26 +02:00
Bojan Mojsilovic 4440e0d499 Fix some styling 2024-06-10 15:06:43 +02:00
Bojan Mojsilovic 23d8bb980b Show all reads for guests 2024-06-10 14:51:03 +02:00
Bojan Mojsilovic f309b2bfc0 Handle USD subscriptions 2024-06-10 13:23:41 +02:00
13 changed files with 266 additions and 53 deletions

View File

@ -55,7 +55,6 @@
gap: 8px;
>button {
color: var(--text-primary);
text-align: center;
font-size: 14px;
font-weight: 600;

View File

@ -53,11 +53,13 @@ const AuthoreSubscribe: Component<{
getAuthorData();
});
const doSubscription = async (tier: Tier, cost: TierCost) => {
const doSubscription = async (tier: Tier, cost: TierCost, exchangeRate?: Record<string, Record<string, number>>) => {
const a = author();
if (!a || !account || !cost) return;
if (cost.unit === 'USD' && (!exchangeRate || !exchangeRate['USD'])) return;
const subEvent = {
kind: Kind.Subscribe,
content: '',
@ -72,13 +74,38 @@ const AuthoreSubscribe: Component<{
],
}
const { success, note } = await sendEvent(subEvent, account.relays, account.relaySettings);
if (success && note) {
await zapSubscription(note, a, account.publicKey, account.relays);
const isZapped = await zapSubscription(note, a, account.publicKey, account.relays, exchangeRate);
if (!isZapped) {
unsubscribe(note.id);
}
}
}
const unsubscribe = async (eventId: string) => {
const a = author();
if (!a || !account) return;
const unsubEvent = {
kind: Kind.Unsubscribe,
content: '',
created_at: Math.floor((new Date()).getTime() / 1_000),
tags: [
['p', a.pubkey],
['e', eventId],
],
};
await sendEvent(unsubEvent, account.relays, account.relaySettings);
}
const openSubscribe = () => {
app?.actions.openAuthorSubscribeModal(author(), doSubscription);
};

View File

@ -65,24 +65,34 @@ const ReedSelect: Component<{ isPhone?: boolean, id?: string, big?: boolean}> =
}
const options:() => SelectionOption[] = () => {
return [
{
label: 'My Reads',
value: account?.publicKey || '',
},
let opts = [];
if (account?.publicKey) {
opts.push(
{
label: 'My Reads',
value: account?.publicKey || '',
}
);
}
opts.push(
{
label: 'All Reads',
value: 'none',
},
}
);
]
return [ ...opts ];
};
const initialValue = () => {
const selected = reeds?.selectedFeed;
if (!selected) {
return options()[0];
const feed = options()[0];
selectFeed(feed);
return feed;
}
return {

View File

@ -20,7 +20,7 @@ import { createStore } from 'solid-js/store';
import { APP_ID } from '../../App';
import { subsTo } from '../../sockets';
import { getArticleThread, getReadsTopics, getUserArticleFeed } from '../../lib/feed';
import { fetchArticles, fetchUserArticles } from '../../handleNotes';
import { fetchUserArticles } from '../../handleNotes';
import { getParametrizedEvent, getParametrizedEvents } from '../../lib/notes';
import { decodeIdentifier } from '../../lib/keys';
import ArticleShort from '../ArticlePreview/ArticleShort';

View File

@ -164,13 +164,13 @@ const ReadsSidebar: Component< { id?: string } > = (props) => {
});
const getRecomendedArticles = async (ids: string[]) => {
if (!account?.publicKey) return;
// if (!account?.publicKey) return;
const subId = `reads_picks_${APP_ID}`;
setIsFetching(() => true);
const articles = await fetchArticles(account.publicKey, ids,subId);
const articles = await fetchArticles(ids,subId);
setIsFetching(() => false);
@ -180,21 +180,22 @@ const ReadsSidebar: Component< { id?: string } > = (props) => {
return (
<div id={props.id} class={styles.readsSidebar}>
<Show when={account?.isKeyLookupDone}>
<div class={styles.headingPicks}>
Featured Author
</div>
<Show
when={!isFetchingAuthors()}
fallback={
<Loader />
}
>
<div class={styles.section}>
<AuthorSubscribe pubkey={featuredAuthor()} />
<Show when={account?.publicKey}>
<div class={styles.headingPicks}>
Featured Author
</div>
</Show>
<Show
when={!isFetchingAuthors()}
fallback={
<Loader />
}
>
<div class={styles.section}>
<AuthorSubscribe pubkey={featuredAuthor()} />
</div>
</Show>
</Show>
<div class={styles.headingPicks}>
Featured Reads

View File

@ -76,7 +76,7 @@
}
}
.body {
.modalBody {
.tiers {
display: flex;
gap: 12px;
@ -94,11 +94,7 @@
padding: 16px;
width: 400px;
&.selected {
border: 1px solid var(--accent);
}
.title: {
.tierTitle {
color: var(--text-primary);
font-size: 20px;
font-weight: 600;
@ -157,6 +153,10 @@
}
}
}
&.selected {
border: 1px solid var(--accent);
}
}
}
}

View File

@ -13,11 +13,17 @@ import { userName } from '../../stores/profile';
import Avatar from '../Avatar/Avatar';
import VerificationCheck from '../VerificationCheck/VerificationCheck';
import { APP_ID } from '../../App';
import { subsTo } from '../../sockets';
import { subsTo, subTo } from '../../sockets';
import { getAuthorSubscriptionTiers } from '../../lib/feed';
import ButtonSecondary from '../Buttons/ButtonSecondary';
import { Select } from '@kobalte/core';
import Loader from '../Loader/Loader';
import { logInfo } from '../../lib/logger';
import { getExchangeRate, getMembershipStatus } from '../../lib/membership';
import { useAccountContext } from '../../contexts/AccountContext';
export const satsInBTC = 100_000_000;
export type TierCost = {
amount: string,
@ -42,23 +48,29 @@ export type TierStore = {
selectedTier: Tier | undefined,
selectedCost: TierCost | undefined,
isFetchingTiers: boolean,
exchangeRate: Record<string, Record<string, number>>,
}
export const payUnits = ['sats', 'msat', ''];
export const payUnits = ['sats', 'sat', 'msat', 'msats', 'USD', 'usd', ''];
const SubscribeToAuthorModal: Component<{
id?: string,
author: PrimalUser | undefined,
onClose: () => void,
onSubscribe: (tier: Tier, cost: TierCost) => void,
onSubscribe: (tier: Tier, cost: TierCost, exchangeRate?: Record<string, Record<string, number>>) => void,
}> = (props) => {
const account = useAccountContext();
const [store, updateStore] = createStore<TierStore>({
tiers: [],
selectedTier: undefined,
selectedCost: undefined,
isFetchingTiers: false,
})
exchangeRate: {},
});
let walletSocket: WebSocket | undefined;
createEffect(() => {
const author = props.author;
@ -68,6 +80,55 @@ const SubscribeToAuthorModal: Component<{
}
});
createEffect(() => {
if (props.author && (!walletSocket || walletSocket.readyState === WebSocket.CLOSED)) {
openWalletSocket(() => {
if (!walletSocket || walletSocket.readyState !== WebSocket.OPEN) return;
const subId = `er_${APP_ID}`;
const unsub = subTo(walletSocket, subId, (type, _, content) => {
if (type === 'EVENT') {
const response: { rate: string } = JSON.parse(content?.content || '{ "rate": 1 }');
const BTCForTarget = parseFloat(response.rate) || 1;
const satsToTarget = BTCForTarget / satsInBTC;
const targetToBTC = 1 / BTCForTarget;
const targetToSats = 1 / satsToTarget;
updateStore('exchangeRate', () => ({
USD: {
sats: targetToSats,
BTC: targetToBTC,
USD: 1,
},
sats: {
sats: 1,
USD: satsToTarget,
BTC: 1 / satsInBTC,
},
BTC: {
sats: satsInBTC,
USD: BTCForTarget,
BTC: 1,
}
}));
}
if (type === 'EOSE') {
unsub();
walletSocket?.close();
}
});
getExchangeRate(account?.publicKey, subId, "USD", walletSocket);
});
} else {
walletSocket?.close();
}
})
const getTiers = (author: PrimalUser) => {
if (!author) return;
@ -84,7 +145,7 @@ const SubscribeToAuthorModal: Component<{
if (content.kind === Kind.Tier) {
const t = content as NostrTier;
const costs = t.tags?.filter((t: string[]) => t[0] === 'amount').map((t: string[]) => (
let costs = t.tags?.filter((t: string[]) => t[0] === 'amount').map((t: string[]) => (
{
amount: t[1],
unit: t[2],
@ -137,9 +198,39 @@ const SubscribeToAuthorModal: Component<{
}
const displayCost = (cost: TierCost | undefined) => {
return `${cost?.unit === 'msat' ? Math.ceil(parseInt(cost?.amount || '0') / 1_000) : cost?.amount} sats`;
let text = '';
switch(cost?.unit) {
case 'msat':
case 'msats':
case '':
text = `${Math.ceil(parseInt(cost?.amount || '0') / 1_000)} sats`;
break;
case 'sats':
case 'sat':
text = `${cost.amount} sats`;
break;
case 'USD':
case 'usd':
text = `${cost.amount} USD`;
}
return text;
};
const openWalletSocket = (onOpen: () => void) => {
walletSocket = new WebSocket('wss://wallet.primal.net/v1');
walletSocket.addEventListener('close', () => {
logInfo('WALLET SOCKET CLOSED');
});
walletSocket.addEventListener('open', () => {
logInfo('WALLET SOCKET OPENED');
onOpen();
});
}
return (
<Modal open={props.author !== undefined} onClose={props.onClose}>
<div id={props.id} class={styles.subscribeToAuthor}>
@ -160,7 +251,7 @@ const SubscribeToAuthorModal: Component<{
</button>
</div>
<div class={styles.body}>
<div class={styles.modalBody}>
<div class={styles.tiers}>
<Show
when={!store.isFetchingTiers}
@ -179,7 +270,7 @@ const SubscribeToAuthorModal: Component<{
class={`${styles.tier} ${isSelectedTier(tier) ? styles.selected : ''}`}
onClick={() => selectTier(tier)}
>
<div class={styles.title}>{tier.title}</div>
<div class={styles.tierTitle}>{tier.title}</div>
<Show
when={costOptions(tier).length > 1 && store.selectedTier?.id === tier.id}
@ -277,7 +368,7 @@ const SubscribeToAuthorModal: Component<{
<Show when={store.selectedTier}>
<div class={styles.payAction}>
<ButtonPrimary
onClick={() => store.selectedTier && store.selectedCost && props.onSubscribe(store.selectedTier, store.selectedCost)}
onClick={() => store.selectedTier && store.selectedCost && props.onSubscribe(store.selectedTier, store.selectedCost, store.exchangeRate)}
>
subscribe
</ButtonPrimary>

View File

@ -492,7 +492,6 @@ export const ReadsProvider = (props: { children: ContextChildren }) => {
if (content.kind === Kind.NoteStats) {
const statistic = content as NostrStatsContent;
const stat = JSON.parse(statistic.content);
console.log('READS STATS: ', stat)
if (scope) {
updateStore(scope, 'page', 'postStats',
@ -527,7 +526,6 @@ export const ReadsProvider = (props: { children: ContextChildren }) => {
const noteActionContent = content as NostrNoteActionsContent;
const noteActions = JSON.parse(noteActionContent.content) as NoteActions;
console.log('READS ACTIONS: ', content)
if (scope) {
updateStore(scope, 'page', 'noteActions',
(actions) => ({ ...actions, [noteActions.event_id]: { ...noteActions } })

View File

@ -184,9 +184,8 @@ export const fetchNotes = (pubkey: string | undefined, noteIds: string[], subId:
});
};
export const fetchArticles = (pubkey: string | undefined, noteIds: string[], subId: string) => {
export const fetchArticles = (noteIds: string[], subId: string) => {
return new Promise<PrimalArticle[]>((resolve, reject) => {
if (!pubkey) reject('Missing pubkey');
let page: FeedPage = {
users: {},

View File

@ -36,3 +36,39 @@ export const getMembershipStatus = async (pubkey: string | undefined, subId: str
return false;
}
}
export const getExchangeRate = async (pubkey: string | undefined, subId: string, currency: string, socket: WebSocket) => {
if (!pubkey) {
return;
}
const content = JSON.stringify(
["exchange_rate", { target_currency: currency }],
);
const event = {
content,
kind: Kind.WALLET_OPERATION,
created_at: Math.ceil((new Date()).getTime() / 1000),
tags: [],
};
const signedEvent = await signEvent(event);
const message = JSON.stringify([
"REQ",
subId,
{cache: ["wallet", { operation_event: signedEvent }]},
]);
if (socket) {
const e = new CustomEvent('send', { detail: { message, ws: socket }});
socket.send(message);
socket.dispatchEvent(e);
} else {
throw('no_socket');
}
}

View File

@ -140,7 +140,7 @@ export const zapProfile = async (profile: PrimalUser, sender: string | undefined
}
}
export const zapSubscription = async (subEvent: NostrRelaySignedEvent, recipient: PrimalUser, sender: string | undefined, relays: Relay[]) => {
export const zapSubscription = async (subEvent: NostrRelaySignedEvent, recipient: PrimalUser, sender: string | undefined, relays: Relay[], exchangeRate?: Record<string, Record<string, number>>) => {
if (!sender || !recipient) {
return false;
}
@ -164,6 +164,11 @@ export const zapSubscription = async (subEvent: NostrRelaySignedEvent, recipient
sats = parseInt(costTag[1]);
}
if (costTag[2] === 'USD' && exchangeRate && exchangeRate['USD']) {
let usd = parseFloat(costTag[1]);
sats = Math.ceil(exchangeRate['USD'].sats * usd * 1_000);
}
let payload = {
profile: recipient.pubkey,
event: subEvent.id,

View File

@ -390,7 +390,7 @@ const Longform: Component< { naddr: string } > = (props) => {
getAuthorSubscriptionTiers(author.pubkey, subId)
}
const doSubscription = async (tier: Tier, cost: TierCost) => {
const doSubscription = async (tier: Tier, cost: TierCost, exchangeRate?: Record<string, Record<string, number>>) => {
const a = store.article?.user;
if (!a || !account || !cost) return;
@ -412,10 +412,34 @@ const Longform: Component< { naddr: string } > = (props) => {
const { success, note } = await sendEvent(subEvent, account.relays, account.relaySettings);
if (success && note) {
await zapSubscription(note, a, account.publicKey, account.relays);
const isZapped = await zapSubscription(note, a, account.publicKey, account.relays, exchangeRate);
if (!isZapped) {
unsubscribe(note.id);
}
}
}
const unsubscribe = async (eventId: string) => {
const a = store.article?.user;
if (!a || !account) return;
const unsubEvent = {
kind: Kind.Unsubscribe,
content: '',
created_at: Math.floor((new Date()).getTime() / 1_000),
tags: [
['p', a.pubkey],
['e', eventId],
],
};
await sendEvent(unsubEvent, account.relays, account.relaySettings);
}
const openSubscribe = () => {
app?.actions.openAuthorSubscribeModal(store.article?.user, doSubscription);
};
@ -602,8 +626,6 @@ const Longform: Component< { naddr: string } > = (props) => {
getArticleThread(account?.publicKey, pubkey, identifier, kind, subId);
}
const updatePage = (content: NostrEventContent) => {
if (content.kind === Kind.Metadata) {
const user = content as NostrUserContent;

View File

@ -547,7 +547,7 @@ const Profile: Component = () => {
getAuthorSubscriptionTiers(author.pubkey, subId);
}
const doSubscription = async (tier: Tier, cost: TierCost) => {
const doSubscription = async (tier: Tier, cost: TierCost, exchangeRate?: Record<string, Record<string, number>>) => {
const a = profile?.userProfile;
if (!a || !account || !cost) return;
@ -569,10 +569,35 @@ const Profile: Component = () => {
const { success, note } = await sendEvent(subEvent, account.relays, account.relaySettings);
if (success && note) {
await zapSubscription(note, a, account.publicKey, account.relays);
const isZapped = await zapSubscription(note, a, account.publicKey, account.relays, exchangeRate);
if (!isZapped) {
unsubscribe(note.id);
}
}
}
const unsubscribe = async (eventId: string) => {
const a = profile?.userProfile;;
if (!a || !account) return;
const unsubEvent = {
kind: Kind.Unsubscribe,
content: '',
created_at: Math.floor((new Date()).getTime() / 1_000),
tags: [
['p', a.pubkey],
['e', eventId],
],
};
await sendEvent(unsubEvent, account.relays, account.relaySettings);
}
const openSubscribe = () => {
app?.actions.openAuthorSubscribeModal(profile?.userProfile, doSubscription);
};