feat: L402 for image/video
This commit is contained in:
parent
c9133cb917
commit
d5032d6439
18
packages/app/src/Cache/PaymentsCache.ts
Normal file
18
packages/app/src/Cache/PaymentsCache.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { Payment, db } from "Db";
|
||||||
|
import FeedCache from "./FeedCache";
|
||||||
|
|
||||||
|
class Payments extends FeedCache<Payment> {
|
||||||
|
constructor() {
|
||||||
|
super("PaymentsCache", db.payments);
|
||||||
|
}
|
||||||
|
|
||||||
|
key(of: Payment): string {
|
||||||
|
return of.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
takeSnapshot(): Array<Payment> {
|
||||||
|
return [...this.cache.values()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PaymentsCache = new Payments();
|
@ -3,7 +3,7 @@ import { FullRelaySettings, HexKey, RawEvent, u256 } from "@snort/nostr";
|
|||||||
import { MetadataCache } from "Cache";
|
import { MetadataCache } from "Cache";
|
||||||
|
|
||||||
export const NAME = "snortDB";
|
export const NAME = "snortDB";
|
||||||
export const VERSION = 8;
|
export const VERSION = 9;
|
||||||
|
|
||||||
export interface SubCache {
|
export interface SubCache {
|
||||||
id: string;
|
id: string;
|
||||||
@ -33,6 +33,13 @@ export interface EventInteraction {
|
|||||||
reposted: boolean;
|
reposted: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Payment {
|
||||||
|
url: string;
|
||||||
|
pr: string;
|
||||||
|
preimage: string;
|
||||||
|
macaroon: string;
|
||||||
|
}
|
||||||
|
|
||||||
const STORES = {
|
const STORES = {
|
||||||
users: "++pubkey, name, display_name, picture, nip05, npub",
|
users: "++pubkey, name, display_name, picture, nip05, npub",
|
||||||
relays: "++addr",
|
relays: "++addr",
|
||||||
@ -40,6 +47,7 @@ const STORES = {
|
|||||||
events: "++id, pubkey, created_at",
|
events: "++id, pubkey, created_at",
|
||||||
dms: "++id, pubkey",
|
dms: "++id, pubkey",
|
||||||
eventInteraction: "++id",
|
eventInteraction: "++id",
|
||||||
|
payments: "++url",
|
||||||
};
|
};
|
||||||
|
|
||||||
export class SnortDB extends Dexie {
|
export class SnortDB extends Dexie {
|
||||||
@ -50,6 +58,7 @@ export class SnortDB extends Dexie {
|
|||||||
events!: Table<RawEvent>;
|
events!: Table<RawEvent>;
|
||||||
dms!: Table<RawEvent>;
|
dms!: Table<RawEvent>;
|
||||||
eventInteraction!: Table<EventInteraction>;
|
eventInteraction!: Table<EventInteraction>;
|
||||||
|
payments!: Table<Payment>;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super(NAME);
|
super(NAME);
|
||||||
|
@ -1,9 +1,16 @@
|
|||||||
import { ProxyImg } from "Element/ProxyImg";
|
import { ProxyImg } from "Element/ProxyImg";
|
||||||
import React, { MouseEvent, useState } from "react";
|
import React, { MouseEvent, useEffect, useState } from "react";
|
||||||
|
import { FormattedMessage, FormattedNumber } from "react-intl";
|
||||||
|
|
||||||
import "./MediaElement.css";
|
import "./MediaElement.css";
|
||||||
import Modal from "Element/Modal";
|
import Modal from "Element/Modal";
|
||||||
import Icon from "Icons/Icon";
|
import Icon from "Icons/Icon";
|
||||||
|
import { decodeInvoice, InvoiceDetails, kvToObject } from "Util";
|
||||||
|
import AsyncButton from "Element/AsyncButton";
|
||||||
|
import { useWallet } from "Wallet";
|
||||||
|
import { PaymentsCache } from "Cache/PaymentsCache";
|
||||||
|
import { Payment } from "Db";
|
||||||
|
import PageSpinner from "Element/PageSpinner";
|
||||||
|
|
||||||
/*
|
/*
|
||||||
[
|
[
|
||||||
@ -21,19 +28,137 @@ interface MediaElementProps {
|
|||||||
blurHash?: string;
|
blurHash?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface L402Object {
|
||||||
|
macaroon: string;
|
||||||
|
invoice: string;
|
||||||
|
}
|
||||||
|
|
||||||
export function MediaElement(props: MediaElementProps) {
|
export function MediaElement(props: MediaElementProps) {
|
||||||
|
const [invoice, setInvoice] = useState<InvoiceDetails>();
|
||||||
|
const [l402, setL402] = useState<L402Object>();
|
||||||
|
const [auth, setAuth] = useState<Payment>();
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [url, setUrl] = useState(props.url);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const wallet = useWallet();
|
||||||
|
|
||||||
|
async function probeFor402() {
|
||||||
|
const cached = await PaymentsCache.get(props.url);
|
||||||
|
if (cached) {
|
||||||
|
setAuth(cached);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = new Request(props.url, {
|
||||||
|
method: "OPTIONS",
|
||||||
|
headers: {
|
||||||
|
accept: "L402",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rsp = await fetch(req);
|
||||||
|
if (rsp.status === 402) {
|
||||||
|
const auth = rsp.headers.get("www-authenticate");
|
||||||
|
if (auth?.startsWith("L402")) {
|
||||||
|
const vals = kvToObject<L402Object>(auth.substring(5));
|
||||||
|
console.debug(vals);
|
||||||
|
setL402(vals);
|
||||||
|
|
||||||
|
if (vals.invoice) {
|
||||||
|
const decoded = decodeInvoice(vals.invoice);
|
||||||
|
setInvoice(decoded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function payInvoice() {
|
||||||
|
if (wallet.wallet && l402) {
|
||||||
|
try {
|
||||||
|
const res = await wallet.wallet.payInvoice(l402.invoice);
|
||||||
|
console.debug(res);
|
||||||
|
if (res.preimage) {
|
||||||
|
const pmt = {
|
||||||
|
pr: l402.invoice,
|
||||||
|
url: props.url,
|
||||||
|
macaroon: l402.macaroon,
|
||||||
|
preimage: res.preimage,
|
||||||
|
};
|
||||||
|
await PaymentsCache.set(pmt);
|
||||||
|
setAuth(pmt);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Error) {
|
||||||
|
setError(e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMedia() {
|
||||||
|
if (!auth) return;
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
const mediaReq = new Request(props.url, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `L402 ${auth.macaroon}:${auth.preimage}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rsp = await fetch(mediaReq);
|
||||||
|
if (rsp.ok) {
|
||||||
|
const buf = await rsp.blob();
|
||||||
|
setUrl(URL.createObjectURL(buf));
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (auth) {
|
||||||
|
loadMedia().catch(console.error);
|
||||||
|
}
|
||||||
|
}, [auth]);
|
||||||
|
|
||||||
|
if (auth && loading) {
|
||||||
|
return <PageSpinner />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invoice) {
|
||||||
|
return (
|
||||||
|
<div className="note-invoice">
|
||||||
|
<h3>
|
||||||
|
<FormattedMessage defaultMessage="Payment Required" />
|
||||||
|
</h3>
|
||||||
|
<div className="flex f-row">
|
||||||
|
<div className="f-grow">
|
||||||
|
<FormattedMessage
|
||||||
|
defaultMessage="You must pay {n} sats to access this file."
|
||||||
|
values={{
|
||||||
|
n: <FormattedNumber value={(invoice.amount ?? 0) / 1000} />,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<AsyncButton onClick={() => payInvoice()}>
|
||||||
|
<FormattedMessage defaultMessage="Pay Now" />
|
||||||
|
</AsyncButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{error && <b className="error">{error}</b>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (props.mime.startsWith("image/")) {
|
if (props.mime.startsWith("image/")) {
|
||||||
return (
|
return (
|
||||||
<SpotlightMedia>
|
<SpotlightMedia>
|
||||||
<ProxyImg key={props.url} src={props.url} />
|
<ProxyImg key={props.url} src={url} onError={() => probeFor402()} />
|
||||||
</SpotlightMedia>
|
</SpotlightMedia>
|
||||||
);
|
);
|
||||||
} else if (props.mime.startsWith("audio/")) {
|
} else if (props.mime.startsWith("audio/")) {
|
||||||
return <audio key={props.url} src={props.url} controls />;
|
return <audio key={props.url} src={url} controls onError={() => probeFor402()} />;
|
||||||
} else if (props.mime.startsWith("video/")) {
|
} else if (props.mime.startsWith("video/")) {
|
||||||
return (
|
return (
|
||||||
<SpotlightMedia>
|
<SpotlightMedia>
|
||||||
<video key={props.url} src={props.url} controls />
|
<video key={props.url} src={url} controls onError={() => probeFor402()} />
|
||||||
</SpotlightMedia>
|
</SpotlightMedia>
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
@ -8,22 +8,13 @@ interface ProxyImgProps extends React.DetailedHTMLProps<React.ImgHTMLAttributes<
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const ProxyImg = (props: ProxyImgProps) => {
|
export const ProxyImg = (props: ProxyImgProps) => {
|
||||||
const { src, size, ...rest } = props;
|
const { proxy } = useImgProxy();
|
||||||
const [url, setUrl] = useState<string>();
|
|
||||||
const [loadFailed, setLoadFailed] = useState(false);
|
const [loadFailed, setLoadFailed] = useState(false);
|
||||||
const [bypass, setBypass] = useState(false);
|
const [bypass, setBypass] = useState(false);
|
||||||
const { proxy } = useImgProxy();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (src) {
|
|
||||||
const url = proxy(src, size);
|
|
||||||
setUrl(url);
|
|
||||||
}
|
|
||||||
}, [src]);
|
|
||||||
|
|
||||||
if (loadFailed) {
|
if (loadFailed) {
|
||||||
if (bypass) {
|
if (bypass) {
|
||||||
return <img src={src} {...rest} />;
|
return <img {...props} />;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@ -35,11 +26,23 @@ export const ProxyImg = (props: ProxyImgProps) => {
|
|||||||
<FormattedMessage
|
<FormattedMessage
|
||||||
defaultMessage="Failed to proxy image from {host}, click here to load directly"
|
defaultMessage="Failed to proxy image from {host}, click here to load directly"
|
||||||
values={{
|
values={{
|
||||||
host: getUrlHostname(src),
|
host: getUrlHostname(props.src),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return <img src={url} {...rest} onError={() => setLoadFailed(true)} />;
|
return (
|
||||||
|
<img
|
||||||
|
{...props}
|
||||||
|
src={props.src ? proxy(props.src, props.size) : ""}
|
||||||
|
onError={e => {
|
||||||
|
if (props.onError) {
|
||||||
|
props.onError(e);
|
||||||
|
} else {
|
||||||
|
setLoadFailed(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
@ -29,6 +29,7 @@ export default function useImgProxy() {
|
|||||||
return {
|
return {
|
||||||
proxy: (url: string, resize?: number) => {
|
proxy: (url: string, resize?: number) => {
|
||||||
if (!settings) return url;
|
if (!settings) return url;
|
||||||
|
if (url.startsWith("data:") || url.startsWith("blob:")) return url;
|
||||||
const opt = resize ? `rs:fit:${resize}:${resize}/dpr:${window.devicePixelRatio}` : "";
|
const opt = resize ? `rs:fit:${resize}:${resize}/dpr:${window.devicePixelRatio}` : "";
|
||||||
const urlBytes = te.encode(url);
|
const urlBytes = te.encode(url);
|
||||||
const urlEncoded = urlSafe(base64.encode(urlBytes, 0, urlBytes.byteLength));
|
const urlEncoded = urlSafe(base64.encode(urlBytes, 0, urlBytes.byteLength));
|
||||||
|
@ -327,6 +327,7 @@ export interface InvoiceDetails {
|
|||||||
descriptionHash?: string;
|
descriptionHash?: string;
|
||||||
paymentHash?: string;
|
paymentHash?: string;
|
||||||
expired: boolean;
|
expired: boolean;
|
||||||
|
pr: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decodeInvoice(pr: string): InvoiceDetails | undefined {
|
export function decodeInvoice(pr: string): InvoiceDetails | undefined {
|
||||||
@ -345,6 +346,7 @@ export function decodeInvoice(pr: string): InvoiceDetails | undefined {
|
|||||||
const descriptionHashSection = parsed.sections.find(a => a.name === "description_hash")?.value;
|
const descriptionHashSection = parsed.sections.find(a => a.name === "description_hash")?.value;
|
||||||
const paymentHashSection = parsed.sections.find(a => a.name === "payment_hash")?.value;
|
const paymentHashSection = parsed.sections.find(a => a.name === "payment_hash")?.value;
|
||||||
const ret = {
|
const ret = {
|
||||||
|
pr,
|
||||||
amount: amount,
|
amount: amount,
|
||||||
expire: timestamp && expire ? timestamp + expire : undefined,
|
expire: timestamp && expire ? timestamp + expire : undefined,
|
||||||
timestamp: timestamp,
|
timestamp: timestamp,
|
||||||
@ -610,3 +612,15 @@ export function sanitizeRelayUrl(url: string) {
|
|||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function kvToObject<T>(o: string, sep?: string) {
|
||||||
|
return Object.fromEntries(
|
||||||
|
o.split(sep ?? ",").map(v => {
|
||||||
|
const match = v.trim().match(/^(\w+)="(.*)"$/);
|
||||||
|
if (match) {
|
||||||
|
return [match[1], match[2]];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
})
|
||||||
|
) as T;
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user