rome -> eslint + prettier
This commit is contained in:
111
src/libs/ndk.tsx
111
src/libs/ndk.tsx
@@ -1,76 +1,79 @@
|
||||
import NDK, {
|
||||
NDKConstructorParams,
|
||||
NDKEvent,
|
||||
NDKFilter,
|
||||
NDKKind,
|
||||
NDKPrivateKeySigner,
|
||||
} from "@nostr-dev-kit/ndk";
|
||||
import { RelayContext } from "@shared/relayProvider";
|
||||
import { FULL_RELAYS } from "@stores/constants";
|
||||
import { useAccount } from "@utils/hooks/useAccount";
|
||||
import { useContext } from "react";
|
||||
NDKConstructorParams,
|
||||
NDKEvent,
|
||||
NDKFilter,
|
||||
NDKKind,
|
||||
NDKPrivateKeySigner,
|
||||
} from '@nostr-dev-kit/ndk';
|
||||
import { useContext } from 'react';
|
||||
|
||||
import { RelayContext } from '@shared/relayProvider';
|
||||
|
||||
import { FULL_RELAYS } from '@stores/constants';
|
||||
|
||||
import { useAccount } from '@utils/hooks/useAccount';
|
||||
|
||||
export async function initNDK(relays?: string[]): Promise<NDK> {
|
||||
const opts: NDKConstructorParams = {};
|
||||
const defaultRelays = new Set(relays || FULL_RELAYS);
|
||||
const opts: NDKConstructorParams = {};
|
||||
const defaultRelays = new Set(relays || FULL_RELAYS);
|
||||
|
||||
opts.explicitRelayUrls = [...defaultRelays];
|
||||
opts.explicitRelayUrls = [...defaultRelays];
|
||||
|
||||
const ndk = new NDK(opts);
|
||||
await ndk.connect(500);
|
||||
const ndk = new NDK(opts);
|
||||
await ndk.connect(500);
|
||||
|
||||
return ndk;
|
||||
return ndk;
|
||||
}
|
||||
|
||||
export async function prefetchEvents(
|
||||
ndk: NDK,
|
||||
filter: NDKFilter,
|
||||
ndk: NDK,
|
||||
filter: NDKFilter
|
||||
): Promise<Set<NDKEvent>> {
|
||||
return new Promise((resolve) => {
|
||||
const events: Map<string, NDKEvent> = new Map();
|
||||
return new Promise((resolve) => {
|
||||
const events: Map<string, NDKEvent> = new Map();
|
||||
|
||||
const relaySetSubscription = ndk.subscribe(filter, {
|
||||
closeOnEose: true,
|
||||
});
|
||||
const relaySetSubscription = ndk.subscribe(filter, {
|
||||
closeOnEose: true,
|
||||
});
|
||||
|
||||
relaySetSubscription.on("event", (event: NDKEvent) => {
|
||||
event.ndk = ndk;
|
||||
events.set(event.tagId(), event);
|
||||
});
|
||||
relaySetSubscription.on('event', (event: NDKEvent) => {
|
||||
event.ndk = ndk;
|
||||
events.set(event.tagId(), event);
|
||||
});
|
||||
|
||||
relaySetSubscription.on("eose", () => {
|
||||
setTimeout(() => resolve(new Set(events.values())), 3000);
|
||||
});
|
||||
});
|
||||
relaySetSubscription.on('eose', () => {
|
||||
setTimeout(() => resolve(new Set(events.values())), 3000);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function usePublish() {
|
||||
const ndk = useContext(RelayContext);
|
||||
const { account } = useAccount();
|
||||
const ndk = useContext(RelayContext);
|
||||
const { account } = useAccount();
|
||||
|
||||
const publish = async ({
|
||||
content,
|
||||
kind,
|
||||
tags,
|
||||
}: {
|
||||
content: string;
|
||||
kind: NDKKind;
|
||||
tags: string[][];
|
||||
}): Promise<NDKEvent> => {
|
||||
const event = new NDKEvent(ndk);
|
||||
const signer = new NDKPrivateKeySigner(account.privkey);
|
||||
const publish = async ({
|
||||
content,
|
||||
kind,
|
||||
tags,
|
||||
}: {
|
||||
content: string;
|
||||
kind: NDKKind;
|
||||
tags: string[][];
|
||||
}): Promise<NDKEvent> => {
|
||||
const event = new NDKEvent(ndk);
|
||||
const signer = new NDKPrivateKeySigner(account.privkey);
|
||||
|
||||
event.content = content;
|
||||
event.kind = kind;
|
||||
event.created_at = Math.floor(Date.now() / 1000);
|
||||
event.pubkey = account.pubkey;
|
||||
event.tags = tags;
|
||||
event.content = content;
|
||||
event.kind = kind;
|
||||
event.created_at = Math.floor(Date.now() / 1000);
|
||||
event.pubkey = account.pubkey;
|
||||
event.tags = tags;
|
||||
|
||||
await event.sign(signer);
|
||||
await event.publish();
|
||||
await event.sign(signer);
|
||||
await event.publish();
|
||||
|
||||
return event;
|
||||
};
|
||||
return event;
|
||||
};
|
||||
|
||||
return publish;
|
||||
return publish;
|
||||
}
|
||||
|
||||
@@ -1,360 +1,349 @@
|
||||
import { OPENGRAPH } from "@stores/constants";
|
||||
import { FetchOptions, ResponseType, fetch } from "@tauri-apps/api/http";
|
||||
import * as cheerio from "cheerio";
|
||||
import { FetchOptions, ResponseType, fetch } from '@tauri-apps/api/http';
|
||||
import * as cheerio from 'cheerio';
|
||||
|
||||
import { OPENGRAPH } from '@stores/constants';
|
||||
|
||||
interface ILinkPreviewOptions {
|
||||
headers?: Record<string, string>;
|
||||
imagesPropertyType?: string;
|
||||
proxyUrl?: string;
|
||||
timeout?: number;
|
||||
followRedirects?: `follow` | `error` | `manual`;
|
||||
resolveDNSHost?: (url: string) => Promise<string>;
|
||||
handleRedirects?: (baseURL: string, forwardedURL: string) => boolean;
|
||||
headers?: Record<string, string>;
|
||||
imagesPropertyType?: string;
|
||||
proxyUrl?: string;
|
||||
timeout?: number;
|
||||
followRedirects?: `follow` | `error` | `manual`;
|
||||
resolveDNSHost?: (url: string) => Promise<string>;
|
||||
handleRedirects?: (baseURL: string, forwardedURL: string) => boolean;
|
||||
}
|
||||
|
||||
interface IPreFetchedResource {
|
||||
headers: Record<string, string>;
|
||||
status?: number;
|
||||
imagesPropertyType?: string;
|
||||
proxyUrl?: string;
|
||||
url: string;
|
||||
data: any;
|
||||
headers: Record<string, string>;
|
||||
status?: number;
|
||||
imagesPropertyType?: string;
|
||||
proxyUrl?: string;
|
||||
url: string;
|
||||
data: any;
|
||||
}
|
||||
|
||||
function metaTag(doc: cheerio.CheerioAPI, type: string, attr: string) {
|
||||
const nodes = doc(`meta[${attr}='${type}']`);
|
||||
return nodes.length ? nodes : null;
|
||||
const nodes = doc(`meta[${attr}='${type}']`);
|
||||
return nodes.length ? nodes : null;
|
||||
}
|
||||
|
||||
function metaTagContent(doc: cheerio.CheerioAPI, type: string, attr: string) {
|
||||
return doc(`meta[${attr}='${type}']`).attr("content");
|
||||
return doc(`meta[${attr}='${type}']`).attr('content');
|
||||
}
|
||||
|
||||
function getTitle(doc: cheerio.CheerioAPI) {
|
||||
let title =
|
||||
metaTagContent(doc, "og:title", "property") ||
|
||||
metaTagContent(doc, "og:title", "name");
|
||||
if (!title) {
|
||||
title = doc("title").text();
|
||||
}
|
||||
return title;
|
||||
let title =
|
||||
metaTagContent(doc, 'og:title', 'property') ||
|
||||
metaTagContent(doc, 'og:title', 'name');
|
||||
if (!title) {
|
||||
title = doc('title').text();
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
function getSiteName(doc: cheerio.CheerioAPI) {
|
||||
const siteName =
|
||||
metaTagContent(doc, "og:site_name", "property") ||
|
||||
metaTagContent(doc, "og:site_name", "name");
|
||||
return siteName;
|
||||
const siteName =
|
||||
metaTagContent(doc, 'og:site_name', 'property') ||
|
||||
metaTagContent(doc, 'og:site_name', 'name');
|
||||
return siteName;
|
||||
}
|
||||
|
||||
function getDescription(doc: cheerio.CheerioAPI) {
|
||||
const description =
|
||||
metaTagContent(doc, "description", "name") ||
|
||||
metaTagContent(doc, "Description", "name") ||
|
||||
metaTagContent(doc, "og:description", "property");
|
||||
return description;
|
||||
const description =
|
||||
metaTagContent(doc, 'description', 'name') ||
|
||||
metaTagContent(doc, 'Description', 'name') ||
|
||||
metaTagContent(doc, 'og:description', 'property');
|
||||
return description;
|
||||
}
|
||||
|
||||
function getMediaType(doc: cheerio.CheerioAPI) {
|
||||
const node = metaTag(doc, "medium", "name");
|
||||
if (node) {
|
||||
const content = node.attr("content");
|
||||
return content === "image" ? "photo" : content;
|
||||
}
|
||||
return (
|
||||
metaTagContent(doc, "og:type", "property") ||
|
||||
metaTagContent(doc, "og:type", "name")
|
||||
);
|
||||
const node = metaTag(doc, 'medium', 'name');
|
||||
if (node) {
|
||||
const content = node.attr('content');
|
||||
return content === 'image' ? 'photo' : content;
|
||||
}
|
||||
return (
|
||||
metaTagContent(doc, 'og:type', 'property') || metaTagContent(doc, 'og:type', 'name')
|
||||
);
|
||||
}
|
||||
|
||||
function getImages(
|
||||
doc: cheerio.CheerioAPI,
|
||||
rootUrl: string,
|
||||
imagesPropertyType?: string,
|
||||
doc: cheerio.CheerioAPI,
|
||||
rootUrl: string,
|
||||
imagesPropertyType?: string
|
||||
) {
|
||||
let images: string[] = [];
|
||||
let nodes: cheerio.Cheerio<cheerio.Element> | null;
|
||||
let src: string | undefined;
|
||||
let dic: Record<string, boolean> = {};
|
||||
let images: string[] = [];
|
||||
let nodes: cheerio.Cheerio<cheerio.Element> | null;
|
||||
let src: string | undefined;
|
||||
let dic: Record<string, boolean> = {};
|
||||
|
||||
const imagePropertyType = imagesPropertyType ?? "og";
|
||||
nodes =
|
||||
metaTag(doc, `${imagePropertyType}:image`, "property") ||
|
||||
metaTag(doc, `${imagePropertyType}:image`, "name");
|
||||
const imagePropertyType = imagesPropertyType ?? 'og';
|
||||
nodes =
|
||||
metaTag(doc, `${imagePropertyType}:image`, 'property') ||
|
||||
metaTag(doc, `${imagePropertyType}:image`, 'name');
|
||||
|
||||
if (nodes) {
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === "tag") {
|
||||
src = node.attribs.content;
|
||||
if (src) {
|
||||
src = new URL(src, rootUrl).href;
|
||||
images.push(src);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (nodes) {
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === 'tag') {
|
||||
src = node.attribs.content;
|
||||
if (src) {
|
||||
src = new URL(src, rootUrl).href;
|
||||
images.push(src);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (images.length <= 0 && !imagesPropertyType) {
|
||||
src = doc("link[rel=image_src]").attr("href");
|
||||
if (src) {
|
||||
src = new URL(src, rootUrl).href;
|
||||
images = [src];
|
||||
} else {
|
||||
nodes = doc("img");
|
||||
if (images.length <= 0 && !imagesPropertyType) {
|
||||
src = doc('link[rel=image_src]').attr('href');
|
||||
if (src) {
|
||||
src = new URL(src, rootUrl).href;
|
||||
images = [src];
|
||||
} else {
|
||||
nodes = doc('img');
|
||||
|
||||
if (nodes?.length) {
|
||||
dic = {};
|
||||
images = [];
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === "tag") src = node.attribs.src;
|
||||
if (src && !dic[src]) {
|
||||
dic[src] = true;
|
||||
// width = node.attribs.width;
|
||||
// height = node.attribs.height;
|
||||
images.push(new URL(src, rootUrl).href);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nodes?.length) {
|
||||
dic = {};
|
||||
images = [];
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === 'tag') src = node.attribs.src;
|
||||
if (src && !dic[src]) {
|
||||
dic[src] = true;
|
||||
// width = node.attribs.width;
|
||||
// height = node.attribs.height;
|
||||
images.push(new URL(src, rootUrl).href);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return images;
|
||||
return images;
|
||||
}
|
||||
|
||||
function getVideos(doc: cheerio.CheerioAPI) {
|
||||
const videos = [];
|
||||
let nodeTypes;
|
||||
let nodeSecureUrls;
|
||||
let nodeType;
|
||||
let nodeSecureUrl;
|
||||
let video;
|
||||
let videoType;
|
||||
let videoSecureUrl;
|
||||
let width;
|
||||
let height;
|
||||
let videoObj;
|
||||
let index;
|
||||
const videos = [];
|
||||
let nodeTypes;
|
||||
let nodeSecureUrls;
|
||||
let nodeType;
|
||||
let nodeSecureUrl;
|
||||
let video;
|
||||
let videoType;
|
||||
let videoSecureUrl;
|
||||
let width;
|
||||
let height;
|
||||
let videoObj;
|
||||
let index;
|
||||
|
||||
const nodes =
|
||||
metaTag(doc, "og:video", "property") || metaTag(doc, "og:video", "name");
|
||||
const nodes = metaTag(doc, 'og:video', 'property') || metaTag(doc, 'og:video', 'name');
|
||||
|
||||
if (nodes?.length) {
|
||||
nodeTypes =
|
||||
metaTag(doc, "og:video:type", "property") ||
|
||||
metaTag(doc, "og:video:type", "name");
|
||||
nodeSecureUrls =
|
||||
metaTag(doc, "og:video:secure_url", "property") ||
|
||||
metaTag(doc, "og:video:secure_url", "name");
|
||||
width =
|
||||
metaTagContent(doc, "og:video:width", "property") ||
|
||||
metaTagContent(doc, "og:video:width", "name");
|
||||
height =
|
||||
metaTagContent(doc, "og:video:height", "property") ||
|
||||
metaTagContent(doc, "og:video:height", "name");
|
||||
if (nodes?.length) {
|
||||
nodeTypes =
|
||||
metaTag(doc, 'og:video:type', 'property') || metaTag(doc, 'og:video:type', 'name');
|
||||
nodeSecureUrls =
|
||||
metaTag(doc, 'og:video:secure_url', 'property') ||
|
||||
metaTag(doc, 'og:video:secure_url', 'name');
|
||||
width =
|
||||
metaTagContent(doc, 'og:video:width', 'property') ||
|
||||
metaTagContent(doc, 'og:video:width', 'name');
|
||||
height =
|
||||
metaTagContent(doc, 'og:video:height', 'property') ||
|
||||
metaTagContent(doc, 'og:video:height', 'name');
|
||||
|
||||
for (index = 0; index < nodes.length; index += 1) {
|
||||
const node = nodes[index];
|
||||
if (node.type === "tag") video = node.attribs.content;
|
||||
for (index = 0; index < nodes.length; index += 1) {
|
||||
const node = nodes[index];
|
||||
if (node.type === 'tag') video = node.attribs.content;
|
||||
|
||||
nodeType = nodeTypes?.[index];
|
||||
if (nodeType?.type === "tag") {
|
||||
videoType = nodeType ? nodeType.attribs.content : null;
|
||||
}
|
||||
nodeType = nodeTypes?.[index];
|
||||
if (nodeType?.type === 'tag') {
|
||||
videoType = nodeType ? nodeType.attribs.content : null;
|
||||
}
|
||||
|
||||
nodeSecureUrl = nodeSecureUrls?.[index];
|
||||
if (nodeSecureUrl?.type === "tag") {
|
||||
videoSecureUrl = nodeSecureUrl ? nodeSecureUrl.attribs.content : null;
|
||||
}
|
||||
nodeSecureUrl = nodeSecureUrls?.[index];
|
||||
if (nodeSecureUrl?.type === 'tag') {
|
||||
videoSecureUrl = nodeSecureUrl ? nodeSecureUrl.attribs.content : null;
|
||||
}
|
||||
|
||||
videoObj = {
|
||||
url: video,
|
||||
secureUrl: videoSecureUrl,
|
||||
type: videoType,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
if (videoType && videoType.indexOf("video/") === 0) {
|
||||
videos.splice(0, 0, videoObj);
|
||||
} else {
|
||||
videos.push(videoObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
videoObj = {
|
||||
url: video,
|
||||
secureUrl: videoSecureUrl,
|
||||
type: videoType,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
if (videoType && videoType.indexOf('video/') === 0) {
|
||||
videos.splice(0, 0, videoObj);
|
||||
} else {
|
||||
videos.push(videoObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return videos;
|
||||
return videos;
|
||||
}
|
||||
|
||||
// returns default favicon (//hostname/favicon.ico) for a url
|
||||
function getDefaultFavicon(rootUrl: string) {
|
||||
return `${new URL(rootUrl).origin}/favicon.ico`;
|
||||
return `${new URL(rootUrl).origin}/favicon.ico`;
|
||||
}
|
||||
|
||||
// returns an array of URLs to favicon images
|
||||
function getFavicons(doc: cheerio.CheerioAPI, rootUrl: string) {
|
||||
const images = [];
|
||||
let nodes: cheerio.Cheerio<cheerio.Element> | never[] = [];
|
||||
let src: string | undefined;
|
||||
const images = [];
|
||||
let nodes: cheerio.Cheerio<cheerio.Element> | never[] = [];
|
||||
let src: string | undefined;
|
||||
|
||||
const relSelectors = [
|
||||
"rel=icon",
|
||||
`rel="shortcut icon"`,
|
||||
"rel=apple-touch-icon",
|
||||
];
|
||||
const relSelectors = ['rel=icon', `rel="shortcut icon"`, 'rel=apple-touch-icon'];
|
||||
|
||||
relSelectors.forEach((relSelector) => {
|
||||
// look for all icon tags
|
||||
nodes = doc(`link[${relSelector}]`);
|
||||
relSelectors.forEach((relSelector) => {
|
||||
// look for all icon tags
|
||||
nodes = doc(`link[${relSelector}]`);
|
||||
|
||||
// collect all images from icon tags
|
||||
if (nodes.length) {
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === "tag") src = node.attribs.href;
|
||||
if (src) {
|
||||
src = new URL(rootUrl).href;
|
||||
images.push(src);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// collect all images from icon tags
|
||||
if (nodes.length) {
|
||||
nodes.each((_: number, node: cheerio.Element) => {
|
||||
if (node.type === 'tag') src = node.attribs.href;
|
||||
if (src) {
|
||||
src = new URL(rootUrl).href;
|
||||
images.push(src);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// if no icon images, use default favicon location
|
||||
if (images.length <= 0) {
|
||||
images.push(getDefaultFavicon(rootUrl));
|
||||
}
|
||||
// if no icon images, use default favicon location
|
||||
if (images.length <= 0) {
|
||||
images.push(getDefaultFavicon(rootUrl));
|
||||
}
|
||||
|
||||
return images;
|
||||
return images;
|
||||
}
|
||||
|
||||
function parseImageResponse(url: string, contentType: string) {
|
||||
return {
|
||||
url,
|
||||
mediaType: "image",
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
return {
|
||||
url,
|
||||
mediaType: 'image',
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
}
|
||||
|
||||
function parseAudioResponse(url: string, contentType: string) {
|
||||
return {
|
||||
url,
|
||||
mediaType: "audio",
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
return {
|
||||
url,
|
||||
mediaType: 'audio',
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
}
|
||||
|
||||
function parseVideoResponse(url: string, contentType: string) {
|
||||
return {
|
||||
url,
|
||||
mediaType: "video",
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
return {
|
||||
url,
|
||||
mediaType: 'video',
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
}
|
||||
|
||||
function parseApplicationResponse(url: string, contentType: string) {
|
||||
return {
|
||||
url,
|
||||
mediaType: "application",
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
return {
|
||||
url,
|
||||
mediaType: 'application',
|
||||
contentType,
|
||||
favicons: [getDefaultFavicon(url)],
|
||||
};
|
||||
}
|
||||
|
||||
function parseTextResponse(
|
||||
body: string,
|
||||
url: string,
|
||||
options: ILinkPreviewOptions = {},
|
||||
contentType?: string,
|
||||
body: string,
|
||||
url: string,
|
||||
options: ILinkPreviewOptions = {},
|
||||
contentType?: string
|
||||
) {
|
||||
const doc = cheerio.load(body);
|
||||
const doc = cheerio.load(body);
|
||||
|
||||
return {
|
||||
url,
|
||||
title: getTitle(doc),
|
||||
siteName: getSiteName(doc),
|
||||
description: getDescription(doc),
|
||||
mediaType: getMediaType(doc) || "website",
|
||||
contentType,
|
||||
images: getImages(doc, url, options.imagesPropertyType),
|
||||
videos: getVideos(doc),
|
||||
favicons: getFavicons(doc, url),
|
||||
};
|
||||
return {
|
||||
url,
|
||||
title: getTitle(doc),
|
||||
siteName: getSiteName(doc),
|
||||
description: getDescription(doc),
|
||||
mediaType: getMediaType(doc) || 'website',
|
||||
contentType,
|
||||
images: getImages(doc, url, options.imagesPropertyType),
|
||||
videos: getVideos(doc),
|
||||
favicons: getFavicons(doc, url),
|
||||
};
|
||||
}
|
||||
|
||||
function parseUnknownResponse(
|
||||
body: string,
|
||||
url: string,
|
||||
options: ILinkPreviewOptions = {},
|
||||
contentType?: string,
|
||||
body: string,
|
||||
url: string,
|
||||
options: ILinkPreviewOptions = {},
|
||||
contentType?: string
|
||||
) {
|
||||
return parseTextResponse(body, url, options, contentType);
|
||||
return parseTextResponse(body, url, options, contentType);
|
||||
}
|
||||
|
||||
function parseResponse(
|
||||
response: IPreFetchedResource,
|
||||
options?: ILinkPreviewOptions,
|
||||
) {
|
||||
try {
|
||||
let contentType = response.headers["content-type"];
|
||||
// console.warn(`original content type`, contentType);
|
||||
if (contentType?.indexOf(";")) {
|
||||
// eslint-disable-next-line prefer-destructuring
|
||||
contentType = contentType.split(";")[0];
|
||||
// console.warn(`splitting content type`, contentType);
|
||||
}
|
||||
function parseResponse(response: IPreFetchedResource, options?: ILinkPreviewOptions) {
|
||||
try {
|
||||
let contentType = response.headers['content-type'];
|
||||
// console.warn(`original content type`, contentType);
|
||||
if (contentType?.indexOf(';')) {
|
||||
// eslint-disable-next-line prefer-destructuring
|
||||
contentType = contentType.split(';')[0];
|
||||
// console.warn(`splitting content type`, contentType);
|
||||
}
|
||||
|
||||
if (!contentType) {
|
||||
return parseUnknownResponse(response.data, response.url, options);
|
||||
}
|
||||
if (!contentType) {
|
||||
return parseUnknownResponse(response.data, response.url, options);
|
||||
}
|
||||
|
||||
if ((contentType as any) instanceof Array) {
|
||||
// eslint-disable-next-line no-param-reassign, prefer-destructuring
|
||||
contentType = contentType[0];
|
||||
}
|
||||
if ((contentType as any) instanceof Array) {
|
||||
// eslint-disable-next-line no-param-reassign, prefer-destructuring
|
||||
contentType = contentType[0];
|
||||
}
|
||||
|
||||
// parse response depending on content type
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_IMAGE.test(contentType)) {
|
||||
return parseImageResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_AUDIO.test(contentType)) {
|
||||
return parseAudioResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_VIDEO.test(contentType)) {
|
||||
return parseVideoResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_TEXT.test(contentType)) {
|
||||
const htmlString = response.data;
|
||||
return parseTextResponse(htmlString, response.url, options, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_APPLICATION.test(contentType)) {
|
||||
return parseApplicationResponse(response.url, contentType);
|
||||
}
|
||||
const htmlString = response.data;
|
||||
return parseUnknownResponse(htmlString, response.url, options);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`link-preview-js could not fetch link information ${(
|
||||
e as any
|
||||
).toString()}`,
|
||||
);
|
||||
}
|
||||
// parse response depending on content type
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_IMAGE.test(contentType)) {
|
||||
return parseImageResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_AUDIO.test(contentType)) {
|
||||
return parseAudioResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_VIDEO.test(contentType)) {
|
||||
return parseVideoResponse(response.url, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_TEXT.test(contentType)) {
|
||||
const htmlString = response.data;
|
||||
return parseTextResponse(htmlString, response.url, options, contentType);
|
||||
}
|
||||
if (OPENGRAPH.REGEX_CONTENT_TYPE_APPLICATION.test(contentType)) {
|
||||
return parseApplicationResponse(response.url, contentType);
|
||||
}
|
||||
const htmlString = response.data;
|
||||
return parseUnknownResponse(htmlString, response.url, options);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`link-preview-js could not fetch link information ${(e as any).toString()}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getLinkPreview(text: string) {
|
||||
const fetchUrl = text;
|
||||
const options: FetchOptions = {
|
||||
method: "GET",
|
||||
timeout: 5,
|
||||
responseType: ResponseType.Text,
|
||||
};
|
||||
const fetchUrl = text;
|
||||
const options: FetchOptions = {
|
||||
method: 'GET',
|
||||
timeout: 5,
|
||||
responseType: ResponseType.Text,
|
||||
};
|
||||
|
||||
let response = await fetch(fetchUrl, options);
|
||||
let response = await fetch(fetchUrl, options);
|
||||
|
||||
if (response.status > 300 && response.status < 309) {
|
||||
const forwardedUrl = response.headers.location || "";
|
||||
response = await fetch(forwardedUrl, options);
|
||||
}
|
||||
if (response.status > 300 && response.status < 309) {
|
||||
const forwardedUrl = response.headers.location || '';
|
||||
response = await fetch(forwardedUrl, options);
|
||||
}
|
||||
|
||||
return parseResponse(response);
|
||||
return parseResponse(response);
|
||||
}
|
||||
|
||||
@@ -1,441 +1,418 @@
|
||||
import { getParentID } from "@utils/transform";
|
||||
import Database from "tauri-plugin-sql-api";
|
||||
import Database from 'tauri-plugin-sql-api';
|
||||
|
||||
import { getParentID } from '@utils/transform';
|
||||
|
||||
let db: null | Database = null;
|
||||
|
||||
// connect database (sqlite)
|
||||
// path: tauri::api::path::BaseDirectory::App
|
||||
export async function connect(): Promise<Database> {
|
||||
if (db) {
|
||||
return db;
|
||||
}
|
||||
db = await Database.load("sqlite:lume.db");
|
||||
return db;
|
||||
if (db) {
|
||||
return db;
|
||||
}
|
||||
db = await Database.load('sqlite:lume.db');
|
||||
return db;
|
||||
}
|
||||
|
||||
// get active account
|
||||
export async function getActiveAccount() {
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
"SELECT * FROM accounts WHERE is_active = 1;",
|
||||
);
|
||||
if (result.length > 0) {
|
||||
return result[0];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
const db = await connect();
|
||||
const result: any = await db.select('SELECT * FROM accounts WHERE is_active = 1;');
|
||||
if (result.length > 0) {
|
||||
return result[0];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// get all accounts
|
||||
export async function getAccounts() {
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
"SELECT * FROM accounts WHERE is_active = 0 ORDER BY created_at DESC;",
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
'SELECT * FROM accounts WHERE is_active = 0 ORDER BY created_at DESC;'
|
||||
);
|
||||
}
|
||||
|
||||
// create account
|
||||
export async function createAccount(
|
||||
npub: string,
|
||||
pubkey: string,
|
||||
privkey: string,
|
||||
follows?: string[][],
|
||||
is_active?: number,
|
||||
npub: string,
|
||||
pubkey: string,
|
||||
privkey: string,
|
||||
follows?: string[][],
|
||||
is_active?: number
|
||||
) {
|
||||
const db = await connect();
|
||||
const res = await db.execute(
|
||||
"INSERT OR IGNORE INTO accounts (npub, pubkey, privkey, follows, is_active) VALUES (?, ?, ?, ?, ?);",
|
||||
[npub, pubkey, privkey, follows || "", is_active || 0],
|
||||
);
|
||||
if (res) {
|
||||
await createBlock(
|
||||
0,
|
||||
"Preserve your freedom",
|
||||
"https://void.cat/d/949GNg7ZjSLHm2eTR3jZqv",
|
||||
);
|
||||
}
|
||||
const getAccount = await getActiveAccount();
|
||||
return getAccount;
|
||||
const db = await connect();
|
||||
const res = await db.execute(
|
||||
'INSERT OR IGNORE INTO accounts (npub, pubkey, privkey, follows, is_active) VALUES (?, ?, ?, ?, ?);',
|
||||
[npub, pubkey, privkey, follows || '', is_active || 0]
|
||||
);
|
||||
if (res) {
|
||||
await createBlock(
|
||||
0,
|
||||
'Preserve your freedom',
|
||||
'https://void.cat/d/949GNg7ZjSLHm2eTR3jZqv'
|
||||
);
|
||||
}
|
||||
const getAccount = await getActiveAccount();
|
||||
return getAccount;
|
||||
}
|
||||
|
||||
// update account
|
||||
export async function updateAccount(
|
||||
column: string,
|
||||
value: string | string[],
|
||||
pubkey: string,
|
||||
column: string,
|
||||
value: string | string[],
|
||||
pubkey: string
|
||||
) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE accounts SET ${column} = ? WHERE pubkey = ?;`,
|
||||
[value, pubkey],
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(`UPDATE accounts SET ${column} = ? WHERE pubkey = ?;`, [
|
||||
value,
|
||||
pubkey,
|
||||
]);
|
||||
}
|
||||
|
||||
// count total notes
|
||||
export async function countTotalChannels() {
|
||||
const db = await connect();
|
||||
const result = await db.select('SELECT COUNT(*) AS "total" FROM channels;');
|
||||
return result[0];
|
||||
const db = await connect();
|
||||
const result = await db.select('SELECT COUNT(*) AS "total" FROM channels;');
|
||||
return result[0];
|
||||
}
|
||||
|
||||
// count total notes
|
||||
export async function countTotalNotes() {
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
'SELECT COUNT(*) AS "total" FROM notes WHERE kind IN (1, 6);',
|
||||
);
|
||||
return parseInt(result[0].total);
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
'SELECT COUNT(*) AS "total" FROM notes WHERE kind IN (1, 6);'
|
||||
);
|
||||
return parseInt(result[0].total);
|
||||
}
|
||||
|
||||
// get all notes
|
||||
export async function getNotes(limit: number, offset: number) {
|
||||
const db = await connect();
|
||||
const totalNotes = await countTotalNotes();
|
||||
const nextCursor = offset + limit;
|
||||
const db = await connect();
|
||||
const totalNotes = await countTotalNotes();
|
||||
const nextCursor = offset + limit;
|
||||
|
||||
const notes: any = { data: null, nextCursor: 0 };
|
||||
const query: any = await db.select(
|
||||
`SELECT * FROM notes WHERE kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`,
|
||||
);
|
||||
const notes: any = { data: null, nextCursor: 0 };
|
||||
const query: any = await db.select(
|
||||
`SELECT * FROM notes WHERE kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`
|
||||
);
|
||||
|
||||
notes["data"] = query;
|
||||
notes["nextCursor"] =
|
||||
Math.round(totalNotes / nextCursor) > 1 ? nextCursor : undefined;
|
||||
notes['data'] = query;
|
||||
notes['nextCursor'] = Math.round(totalNotes / nextCursor) > 1 ? nextCursor : undefined;
|
||||
|
||||
return notes;
|
||||
return notes;
|
||||
}
|
||||
|
||||
// get all notes by pubkey
|
||||
export async function getNotesByPubkey(pubkey: string) {
|
||||
const db = await connect();
|
||||
const res: any = await db.select(
|
||||
`SELECT * FROM notes WHERE pubkey == "${pubkey}" AND kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC;`,
|
||||
);
|
||||
const db = await connect();
|
||||
const res: any = await db.select(
|
||||
`SELECT * FROM notes WHERE pubkey == "${pubkey}" AND kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC;`
|
||||
);
|
||||
|
||||
return res;
|
||||
return res;
|
||||
}
|
||||
|
||||
// get all notes by authors
|
||||
export async function getNotesByAuthors(
|
||||
authors: string,
|
||||
limit: number,
|
||||
offset: number,
|
||||
) {
|
||||
const db = await connect();
|
||||
const totalNotes = await countTotalNotes();
|
||||
const nextCursor = offset + limit;
|
||||
const array = JSON.parse(authors);
|
||||
const finalArray = `'${array.join("','")}'`;
|
||||
export async function getNotesByAuthors(authors: string, limit: number, offset: number) {
|
||||
const db = await connect();
|
||||
const totalNotes = await countTotalNotes();
|
||||
const nextCursor = offset + limit;
|
||||
const array = JSON.parse(authors);
|
||||
const finalArray = `'${array.join("','")}'`;
|
||||
|
||||
const notes: any = { data: null, nextCursor: 0 };
|
||||
const query: any = await db.select(
|
||||
`SELECT * FROM notes WHERE pubkey IN (${finalArray}) AND kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`,
|
||||
);
|
||||
const notes: any = { data: null, nextCursor: 0 };
|
||||
const query: any = await db.select(
|
||||
`SELECT * FROM notes WHERE pubkey IN (${finalArray}) AND kind IN (1, 6, 1063) GROUP BY parent_id ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`
|
||||
);
|
||||
|
||||
notes["data"] = query;
|
||||
notes["nextCursor"] =
|
||||
Math.round(totalNotes / nextCursor) > 1 ? nextCursor : undefined;
|
||||
notes['data'] = query;
|
||||
notes['nextCursor'] = Math.round(totalNotes / nextCursor) > 1 ? nextCursor : undefined;
|
||||
|
||||
return notes;
|
||||
return notes;
|
||||
}
|
||||
|
||||
// get note by id
|
||||
export async function getNoteByID(event_id: string) {
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
`SELECT * FROM notes WHERE event_id = "${event_id}";`,
|
||||
);
|
||||
return result[0];
|
||||
const db = await connect();
|
||||
const result = await db.select(`SELECT * FROM notes WHERE event_id = "${event_id}";`);
|
||||
return result[0];
|
||||
}
|
||||
|
||||
// create note
|
||||
export async function createNote(
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
tags: any,
|
||||
content: string,
|
||||
created_at: number,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
tags: any,
|
||||
content: string,
|
||||
created_at: number
|
||||
) {
|
||||
const db = await connect();
|
||||
const account = await getActiveAccount();
|
||||
const parentID = getParentID(tags, event_id);
|
||||
const db = await connect();
|
||||
const account = await getActiveAccount();
|
||||
const parentID = getParentID(tags, event_id);
|
||||
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO notes (event_id, account_id, pubkey, kind, tags, content, created_at, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?);",
|
||||
[event_id, account.id, pubkey, kind, tags, content, created_at, parentID],
|
||||
);
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO notes (event_id, account_id, pubkey, kind, tags, content, created_at, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
|
||||
[event_id, account.id, pubkey, kind, tags, content, created_at, parentID]
|
||||
);
|
||||
}
|
||||
|
||||
// get note replies
|
||||
export async function getReplies(parent_id: string) {
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT * FROM replies WHERE parent_id = "${parent_id}" ORDER BY created_at DESC;`,
|
||||
);
|
||||
return result;
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT * FROM replies WHERE parent_id = "${parent_id}" ORDER BY created_at DESC;`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
// create reply note
|
||||
export async function createReplyNote(
|
||||
parent_id: string,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
tags: any,
|
||||
content: string,
|
||||
created_at: number,
|
||||
parent_id: string,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
tags: any,
|
||||
content: string,
|
||||
created_at: number
|
||||
) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO replies (event_id, parent_id, pubkey, kind, tags, content, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);",
|
||||
[event_id, parent_id, pubkey, kind, tags, content, created_at],
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO replies (event_id, parent_id, pubkey, kind, tags, content, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);',
|
||||
[event_id, parent_id, pubkey, kind, tags, content, created_at]
|
||||
);
|
||||
}
|
||||
|
||||
// get all channels
|
||||
export async function getChannels() {
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
"SELECT * FROM channels ORDER BY created_at DESC;",
|
||||
);
|
||||
return result;
|
||||
const db = await connect();
|
||||
const result: any = await db.select('SELECT * FROM channels ORDER BY created_at DESC;');
|
||||
return result;
|
||||
}
|
||||
|
||||
// get channel by id
|
||||
export async function getChannel(id: string) {
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
`SELECT * FROM channels WHERE event_id = "${id}";`,
|
||||
);
|
||||
return result[0];
|
||||
const db = await connect();
|
||||
const result = await db.select(`SELECT * FROM channels WHERE event_id = "${id}";`);
|
||||
return result[0];
|
||||
}
|
||||
|
||||
// create channel
|
||||
export async function createChannel(
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
name: string,
|
||||
picture: string,
|
||||
about: string,
|
||||
created_at: number,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
name: string,
|
||||
picture: string,
|
||||
about: string,
|
||||
created_at: number
|
||||
) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO channels (event_id, pubkey, name, picture, about, created_at) VALUES (?, ?, ?, ?, ?, ?);",
|
||||
[event_id, pubkey, name, picture, about, created_at],
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO channels (event_id, pubkey, name, picture, about, created_at) VALUES (?, ?, ?, ?, ?, ?);',
|
||||
[event_id, pubkey, name, picture, about, created_at]
|
||||
);
|
||||
}
|
||||
|
||||
// update channel metadata
|
||||
export async function updateChannelMetadata(event_id: string, value: string) {
|
||||
const db = await connect();
|
||||
const data = JSON.parse(value);
|
||||
const db = await connect();
|
||||
const data = JSON.parse(value);
|
||||
|
||||
return await db.execute(
|
||||
"UPDATE channels SET name = ?, picture = ?, about = ? WHERE event_id = ?;",
|
||||
[data.name, data.picture, data.about, event_id],
|
||||
);
|
||||
return await db.execute(
|
||||
'UPDATE channels SET name = ?, picture = ?, about = ? WHERE event_id = ?;',
|
||||
[data.name, data.picture, data.about, event_id]
|
||||
);
|
||||
}
|
||||
|
||||
// create channel messages
|
||||
export async function createChannelMessage(
|
||||
channel_id: string,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
content: string,
|
||||
tags: string[][],
|
||||
created_at: number,
|
||||
channel_id: string,
|
||||
event_id: string,
|
||||
pubkey: string,
|
||||
kind: number,
|
||||
content: string,
|
||||
tags: string[][],
|
||||
created_at: number
|
||||
) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO channel_messages (channel_id, event_id, pubkey, kind, content, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);",
|
||||
[channel_id, event_id, pubkey, kind, content, tags, created_at],
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO channel_messages (channel_id, event_id, pubkey, kind, content, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);',
|
||||
[channel_id, event_id, pubkey, kind, content, tags, created_at]
|
||||
);
|
||||
}
|
||||
|
||||
// get channel messages by channel id
|
||||
export async function getChannelMessages(channel_id: string) {
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT * FROM channel_messages WHERE channel_id = "${channel_id}" ORDER BY created_at ASC;`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT * FROM channel_messages WHERE channel_id = "${channel_id}" ORDER BY created_at ASC;`
|
||||
);
|
||||
}
|
||||
|
||||
// get channel users
|
||||
export async function getChannelUsers(channel_id: string) {
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT DISTINCT pubkey FROM channel_messages WHERE channel_id = "${channel_id}";`,
|
||||
);
|
||||
return result;
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT DISTINCT pubkey FROM channel_messages WHERE channel_id = "${channel_id}";`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
// get all chats by pubkey
|
||||
export async function getChatsByPubkey(pubkey: string) {
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT DISTINCT sender_pubkey FROM chats WHERE receiver_pubkey = "${pubkey}" ORDER BY created_at DESC;`,
|
||||
);
|
||||
const newArr: any = result.map((v) => ({ ...v, new_messages: 0 }));
|
||||
return newArr;
|
||||
const db = await connect();
|
||||
const result: any = await db.select(
|
||||
`SELECT DISTINCT sender_pubkey FROM chats WHERE receiver_pubkey = "${pubkey}" ORDER BY created_at DESC;`
|
||||
);
|
||||
const newArr: any = result.map((v) => ({ ...v, new_messages: 0 }));
|
||||
return newArr;
|
||||
}
|
||||
|
||||
// get chat messages
|
||||
export async function getChatMessages(
|
||||
receiver_pubkey: string,
|
||||
sender_pubkey: string,
|
||||
) {
|
||||
const db = await connect();
|
||||
let receiver = [];
|
||||
export async function getChatMessages(receiver_pubkey: string, sender_pubkey: string) {
|
||||
const db = await connect();
|
||||
let receiver = [];
|
||||
|
||||
const sender: any = await db.select(
|
||||
`SELECT * FROM chats WHERE sender_pubkey = "${sender_pubkey}" AND receiver_pubkey = "${receiver_pubkey}";`,
|
||||
);
|
||||
const sender: any = await db.select(
|
||||
`SELECT * FROM chats WHERE sender_pubkey = "${sender_pubkey}" AND receiver_pubkey = "${receiver_pubkey}";`
|
||||
);
|
||||
|
||||
if (receiver_pubkey !== sender_pubkey) {
|
||||
receiver = await db.select(
|
||||
`SELECT * FROM chats WHERE sender_pubkey = "${receiver_pubkey}" AND receiver_pubkey = "${sender_pubkey}";`,
|
||||
);
|
||||
}
|
||||
if (receiver_pubkey !== sender_pubkey) {
|
||||
receiver = await db.select(
|
||||
`SELECT * FROM chats WHERE sender_pubkey = "${receiver_pubkey}" AND receiver_pubkey = "${sender_pubkey}";`
|
||||
);
|
||||
}
|
||||
|
||||
const result = [...sender, ...receiver].sort(
|
||||
(x: { created_at: number }, y: { created_at: number }) =>
|
||||
x.created_at - y.created_at,
|
||||
);
|
||||
const result = [...sender, ...receiver].sort(
|
||||
(x: { created_at: number }, y: { created_at: number }) => x.created_at - y.created_at
|
||||
);
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
// create chat
|
||||
export async function createChat(
|
||||
event_id: string,
|
||||
receiver_pubkey: string,
|
||||
sender_pubkey: string,
|
||||
content: string,
|
||||
tags: string[][],
|
||||
created_at: number,
|
||||
event_id: string,
|
||||
receiver_pubkey: string,
|
||||
sender_pubkey: string,
|
||||
content: string,
|
||||
tags: string[][],
|
||||
created_at: number
|
||||
) {
|
||||
const db = await connect();
|
||||
await db.execute(
|
||||
"INSERT OR IGNORE INTO chats (event_id, receiver_pubkey, sender_pubkey, content, tags, created_at) VALUES (?, ?, ?, ?, ?, ?);",
|
||||
[event_id, receiver_pubkey, sender_pubkey, content, tags, created_at],
|
||||
);
|
||||
return sender_pubkey;
|
||||
const db = await connect();
|
||||
await db.execute(
|
||||
'INSERT OR IGNORE INTO chats (event_id, receiver_pubkey, sender_pubkey, content, tags, created_at) VALUES (?, ?, ?, ?, ?, ?);',
|
||||
[event_id, receiver_pubkey, sender_pubkey, content, tags, created_at]
|
||||
);
|
||||
return sender_pubkey;
|
||||
}
|
||||
|
||||
// get setting
|
||||
export async function getSetting(key: string) {
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
`SELECT value FROM settings WHERE key = "${key}";`,
|
||||
);
|
||||
return result[0]?.value;
|
||||
const db = await connect();
|
||||
const result = await db.select(`SELECT value FROM settings WHERE key = "${key}";`);
|
||||
return result[0]?.value;
|
||||
}
|
||||
|
||||
// update setting
|
||||
export async function updateSetting(key: string, value: string | number) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE settings SET value = "${value}" WHERE key = "${key}";`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(`UPDATE settings SET value = "${value}" WHERE key = "${key}";`);
|
||||
}
|
||||
|
||||
// get last login
|
||||
export async function getLastLogin() {
|
||||
const db = await connect();
|
||||
const result = await db.select(
|
||||
`SELECT value FROM settings WHERE key = "last_login";`,
|
||||
);
|
||||
if (result[0]) {
|
||||
return parseInt(result[0].value);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
const db = await connect();
|
||||
const result = await db.select(`SELECT value FROM settings WHERE key = "last_login";`);
|
||||
if (result[0]) {
|
||||
return parseInt(result[0].value);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// update last login
|
||||
export async function updateLastLogin(value: number) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE settings SET value = ${value} WHERE key = "last_login";`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE settings SET value = ${value} WHERE key = "last_login";`
|
||||
);
|
||||
}
|
||||
|
||||
// get blacklist by kind and account id
|
||||
export async function getBlacklist(account_id: number, kind: number) {
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT * FROM blacklist WHERE account_id = "${account_id}" AND kind = "${kind}";`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT * FROM blacklist WHERE account_id = "${account_id}" AND kind = "${kind}";`
|
||||
);
|
||||
}
|
||||
|
||||
// get active blacklist by kind and account id
|
||||
export async function getActiveBlacklist(account_id: number, kind: number) {
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT content FROM blacklist WHERE account_id = "${account_id}" AND kind = "${kind}" AND status = 1;`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.select(
|
||||
`SELECT content FROM blacklist WHERE account_id = "${account_id}" AND kind = "${kind}" AND status = 1;`
|
||||
);
|
||||
}
|
||||
|
||||
// add to blacklist
|
||||
export async function addToBlacklist(
|
||||
account_id: number,
|
||||
content: string,
|
||||
kind: number,
|
||||
status?: number,
|
||||
account_id: number,
|
||||
content: string,
|
||||
kind: number,
|
||||
status?: number
|
||||
) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO blacklist (account_id, content, kind, status) VALUES (?, ?, ?, ?);",
|
||||
[account_id, content, kind, status || 1],
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO blacklist (account_id, content, kind, status) VALUES (?, ?, ?, ?);',
|
||||
[account_id, content, kind, status || 1]
|
||||
);
|
||||
}
|
||||
|
||||
// update item in blacklist
|
||||
export async function updateItemInBlacklist(content: string, status: number) {
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE blacklist SET status = "${status}" WHERE content = "${content}";`,
|
||||
);
|
||||
const db = await connect();
|
||||
return await db.execute(
|
||||
`UPDATE blacklist SET status = "${status}" WHERE content = "${content}";`
|
||||
);
|
||||
}
|
||||
|
||||
// get all blocks
|
||||
export async function getBlocks() {
|
||||
const db = await connect();
|
||||
const activeAccount = await getActiveAccount();
|
||||
const result: any = await db.select(
|
||||
`SELECT * FROM blocks WHERE account_id = "${activeAccount.id}" ORDER BY created_at DESC;`,
|
||||
);
|
||||
return result;
|
||||
const db = await connect();
|
||||
const activeAccount = await getActiveAccount();
|
||||
const result: any = await db.select(
|
||||
`SELECT * FROM blocks WHERE account_id = "${activeAccount.id}" ORDER BY created_at DESC;`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
// create block
|
||||
export async function createBlock(kind: number, title: string, content: any) {
|
||||
const db = await connect();
|
||||
const activeAccount = await getActiveAccount();
|
||||
return await db.execute(
|
||||
"INSERT OR IGNORE INTO blocks (account_id, kind, title, content) VALUES (?, ?, ?, ?);",
|
||||
[activeAccount.id, kind, title, content],
|
||||
);
|
||||
const db = await connect();
|
||||
const activeAccount = await getActiveAccount();
|
||||
return await db.execute(
|
||||
'INSERT OR IGNORE INTO blocks (account_id, kind, title, content) VALUES (?, ?, ?, ?);',
|
||||
[activeAccount.id, kind, title, content]
|
||||
);
|
||||
}
|
||||
|
||||
// remove block
|
||||
export async function removeBlock(id: string) {
|
||||
const db = await connect();
|
||||
return await db.execute(`DELETE FROM blocks WHERE id = "${id}";`);
|
||||
const db = await connect();
|
||||
return await db.execute(`DELETE FROM blocks WHERE id = "${id}";`);
|
||||
}
|
||||
|
||||
// logout
|
||||
export async function removeAll() {
|
||||
const db = await connect();
|
||||
await db.execute(`UPDATE settings SET value = "0" WHERE key = "last_login";`);
|
||||
await db.execute("DELETE FROM replies;");
|
||||
await db.execute("DELETE FROM notes;");
|
||||
await db.execute("DELETE FROM blacklist;");
|
||||
await db.execute("DELETE FROM blocks;");
|
||||
await db.execute("DELETE FROM chats;");
|
||||
await db.execute("DELETE FROM accounts;");
|
||||
return true;
|
||||
const db = await connect();
|
||||
await db.execute(`UPDATE settings SET value = "0" WHERE key = "last_login";`);
|
||||
await db.execute('DELETE FROM replies;');
|
||||
await db.execute('DELETE FROM notes;');
|
||||
await db.execute('DELETE FROM blacklist;');
|
||||
await db.execute('DELETE FROM blocks;');
|
||||
await db.execute('DELETE FROM chats;');
|
||||
await db.execute('DELETE FROM accounts;');
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user