aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2023-01-17 11:53:24 -0800
committerAdam Soltys <[email protected]>2023-01-17 11:53:24 -0800
commite918a818acf789a6619cbf4432f0c4713d4c53e6 (patch)
tree0d30f8b6e519aaf31079f337e8808992f63f92ef
parent46913d34e77f19c3dd7c105b1deec452348dd1db (diff)
downloadcoinos-server-e918a818acf789a6619cbf4432f0c4713d4c53e6.tar.gz
coinos-server-e918a818acf789a6619cbf4432f0c4713d4c53e6.zip
nostr cleanup
-rw-r--r--index.js2
-rw-r--r--lib/locations.js6
-rw-r--r--lib/nostr.js332
-rw-r--r--lib/rates.js3
-rw-r--r--lib/sendInternal.js5
-rw-r--r--lib/sockets.js8
-rw-r--r--lib/upload.js51
-rw-r--r--routes/events.js1
-rw-r--r--routes/locations.js8
-rw-r--r--routes/nostr.js32
-rw-r--r--routes/send.js2
-rw-r--r--sampleconfig/index.js2
12 files changed, 128 insertions, 324 deletions
diff --git a/index.js b/index.js
index ec0e4244..9d291355 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,7 @@
import app from "$app";
import { auth, optional } from "$lib/auth";
+import { fillPool } from "$lib/nostr";
import { listenForLightning } from "$lib/lightning";
import { getLocations } from "$lib/locations";
import { getRates, sendRates } from "$lib/rates";
@@ -15,6 +16,7 @@ import users from "$routes/users";
import payments from "$routes/payments";
import requests from "$routes/requests";
+fillPool();
listenForLightning();
getLocations();
diff --git a/lib/locations.js b/lib/locations.js
index bd2cfb5e..39883555 100644
--- a/lib/locations.js
+++ b/lib/locations.js
@@ -8,10 +8,8 @@ export let getLocations = async () => {
).json();
locations = locations.filter(
- l =>
- l["osm_json"].tags && l["osm_json"].tags["payment:coinos"] === "yes"
- )
-
+ l => l["osm_json"].tags && l["osm_json"].tags["payment:coinos"] === "yes"
+ );
await s("locations", locations);
} catch (e) {}
diff --git a/lib/nostr.js b/lib/nostr.js
index 93370587..d4dc2e67 100644
--- a/lib/nostr.js
+++ b/lib/nostr.js
@@ -7,16 +7,81 @@ import { g, s, db } from "$lib/db";
import { nada, wait } from "$lib/utils";
export let pool;
-try {
+
+export let fillPool = () => {
pool = RelayPool(config.relays);
-} catch (e) {
- console.log(e);
-}
+ pool.on("open", relay => {
+ if (relay.url.includes(config.relay)) coinos = relay;
+ relay.subscribe("live", { limit: 1 });
+ });
+
+ pool.on("event", async (relay, sub, ev) => {
+ if (timeouts[sub]) timeouts[sub].extend(ev);
+ try {
+ let content;
+ try {
+ content = JSON.parse(ev.content);
+ } catch (e) {
+ content = ev.content;
+ }
+
+ if (sub === "live") {
+ let { pubkey } = ev;
+
+ if (Math.abs(Math.floor(Date.now() / 1000) - ev.created_at) > 7200)
+ return;
+
+ if (seen.includes(ev.id)) return;
+ seen.push(ev.id);
+ seen.length > 1000 && seen.shift();
+
+ if (coinos && ev.kind < 5) {
+ // coinos.send(["EVENT", ev]);
+ ev.user = await getUser(pubkey);
+ // broadcast("event", ev);
+ }
+ } else if (sub.includes("profile")) {
+ let { pubkey } = ev;
+ let user = await getUser(pubkey);
+
+ if (user.updated > ev.created_at) return;
-pool.on("open", relay => {
- if (relay.url.includes(config.relay)) coinos = relay;
- relay.subscribe("live", { limit: 1 });
-});
+ if (content.name && user.username === pubkey.substr(0, 6))
+ user.username = content.name;
+
+ delete content.name;
+
+ user = {
+ ...user,
+ ...content,
+ updated: ev.created_at
+ };
+
+ await s(`user:${pubkey}`, JSON.stringify(user));
+ coinos.send(ev);
+ } else if (sub.includes("follows")) {
+ let pubkey = sub.split(":")[0];
+ await s(`${pubkey}:follows`, JSON.stringify(ev.tags));
+ for (let f of ev.tags) {
+ let [_, followPubkey] = f;
+ await db.sAdd(`${followPubkey}:followers`, pubkey);
+ }
+ coinos.send(ev);
+ } else if (sub.includes("followers")) {
+ let followed = sub.split(":")[0];
+ let { pubkey } = ev;
+ await db.sAdd(`${followed}:followers`, pubkey);
+ coinos.send(ev);
+ } else if (sub.includes("notes")) {
+ let pubkey = sub.split(":")[0];
+ await db.sAdd(pubkey, ev.id);
+ await s(`ev:${ev.id}`, JSON.stringify(ev));
+ }
+ } catch (e) {
+ console.log(e);
+ }
+ });
+};
export let coinos;
let now = () => Math.round(Date.now() / 1000);
@@ -97,254 +162,3 @@ let getUser = async pubkey =>
pubkey,
anon: true
};
-
-pool.on("event", async (relay, sub, ev) => {
- if (timeouts[sub]) timeouts[sub].extend(ev);
- try {
- let content;
- try {
- content = JSON.parse(ev.content);
- } catch (e) {
- content = ev.content;
- }
-
- if (sub === "live") {
- let { pubkey } = ev;
-
- if (Math.abs(Math.floor(Date.now() / 1000) - ev.created_at) > 7200)
- return;
-
- if (seen.includes(ev.id)) return;
- seen.push(ev.id);
- seen.length > 1000 && seen.shift();
-
- if (coinos && ev.kind < 5) {
- // coinos.send(["EVENT", ev]);
- ev.user = await getUser(pubkey);
- // broadcast("event", ev);
- }
- } else if (sub.includes("profile")) {
- let { pubkey } = ev;
- let user = await getUser(pubkey);
-
- if (user.updated > ev.created_at) return;
-
- if (content.name && user.username === pubkey.substr(0, 6))
- user.username = content.name;
-
- delete content.name;
-
- user = {
- ...user,
- ...content,
- updated: ev.created_at
- };
-
- await s(`user:${pubkey}`, JSON.stringify(user));
- coinos.send(ev);
- } else if (sub.includes("follows")) {
- let pubkey = sub.split(":")[0];
- await s(`${pubkey}:follows`, JSON.stringify(ev.tags));
- for (let f of ev.tags) {
- let [_, followPubkey] = f;
- await db.sAdd(`${followPubkey}:followers`, pubkey);
- }
- coinos.send(ev);
- } else if (sub.includes("followers")) {
- let followed = sub.split(":")[0];
- let { pubkey } = ev;
- await db.sAdd(`${followed}:followers`, pubkey);
- coinos.send(ev);
- } else if (sub.includes("notes")) {
- let pubkey = sub.split(":")[0];
- await db.sAdd(pubkey, ev.id);
- await s(`ev:${ev.id}`, JSON.stringify(ev));
- }
- } catch (e) {
- console.log(e);
- }
-});
-
-export default {
-async event (req, res) {
- try {
- let event = JSON.parse(await g(`ev:${req.params.id}`));
- let { pubkey } = event;
-
- event.user = JSON.parse(await g(`user:${pubkey}`)) || {
- username: pubkey.substr(0, 6),
- pubkey,
- anon: true,
- follows: [],
- followers: []
- };
-
- res.send(event);
- } catch (e) {
- res.code(500).send("Problem fetching event");
- }
-},
-
-async notes (req, res) {
- try {
- let { pubkey } = req.params;
-
- let user = JSON.parse(await g(`user:${pubkey}`));
-
- if (!user) {
- user = await db.User.findOne({
- where: { pubkey }
- });
- }
-
- if (!user)
- user = {
- username: pubkey.substr(0, 6),
- pubkey,
- anon: true,
- follows: [],
- followers: []
- };
-
- q(
- `${pubkey}:notes`,
- {
- kinds: [1],
- authors: [pubkey]
- },
- { since: 0 }
- ).catch(nada);
-
- await g(`user:${pubkey}`, JSON.stringify(user));
-
- let ids = await db.sMembers(pubkey);
-
- let events = ids.length
- ? (await db.mGet(ids.map(k => "ev:" + k))).map(JSON.parse)
- : [];
-
- res.send(events.map(e => ({ ...e, user })));
- } catch (e) {
- console.log(e);
- res.code(500).send("problem fetching user events");
- }
-},
-
-async broadcast (req, res) {
- let { event } = req.body;
- pool.send(["EVENT", event]);
- res.send(event);
-},
-
-async follows (req, res) {
- try {
- let { pubkey } = req.params;
- let { tagsonly } = req.query;
-
- let sub = `${pubkey}:follows`;
- q(
- sub,
- {
- limit: 1,
- kinds: [3],
- authors: [pubkey]
- },
- { timeout: 60000, eager: 60000 }
- ).catch(nada);
-
- let tags = JSON.parse(await g(`${pubkey}:follows`)) || [];
- if (tagsonly) return res.send(tags);
-
- let follows = [];
- for (let f of tags) {
- let [_, pubkey] = f;
-
- q(`${pubkey}:profile:f1`, {
- limit: 1,
- kinds: [0],
- authors: [pubkey]
- }).catch(nada);
-
- let user = JSON.parse(await g(`user:${pubkey}`));
-
- if (!user)
- user = {
- username: pubkey.substr(0, 6),
- pubkey,
- anon: true
- };
-
- follows.push(user);
- }
-
- follows = uniq(follows, e => e.pubkey);
- follows.sort((a, b) => a.username.localeCompare(b.username));
-
- res.send(follows);
- } catch (e) {
- console.log(e);
- res.code(500).send(e && e.message);
- }
-});
-
-async (req, res) followers {
- try {
- let { pubkey } = req.params;
-
- let pubkeys = [
- ...new Set([
- ...(await got(`${config.nostr}/followers?pubkey=${pubkey}`).json()),
- ...(await db.sMembers(`${pubkey}:followers`))
- ])
- ];
-
- let followers = [];
-
- q(
- `${pubkey}:followers`,
- { kinds: [3], "#p": [pubkey] },
- { timeout: 60000, eager: 60000 }
- ).catch(nada);
-
- for (let pubkey of pubkeys) {
- let user = JSON.parse(await g(`user:${pubkey}`));
- if (!user || !user.updated) {
- q(`${pubkey}:profile:f2`, {
- limit: 1,
- kinds: [0],
- authors: [pubkey]
- }).catch(nada);
-
- user = JSON.parse(await g(`user:${pubkey}`));
- }
-
- if (!user)
- user = {
- username: pubkey.substr(0, 6),
- pubkey,
- anon: true
- };
-
- followers.push(user);
- }
-
- followers = uniq(followers, e => e.pubkey);
- followers.sort((a, b) => a.username.localeCompare(b.username));
-
- res.send(followers);
- } catch (e) {
- console.log(e);
- res.code(500).send(e && e.message);
- }
-},
-
-async identities (req, res) {
- res.send({
- names: {
- adam: "566c166f3adab0c8fba5da015b0b3bcc8eb3696b455f2a1d43bfbd97059646a8",
- asoltys:
- "566c166f3adab0c8fba5da015b0b3bcc8eb3696b455f2a1d43bfbd97059646a8"
- }
- });
-}
-}
diff --git a/lib/rates.js b/lib/rates.js
index 00e1bd88..6f87c78e 100644
--- a/lib/rates.js
+++ b/lib/rates.js
@@ -37,7 +37,8 @@ export let sendRates = () => broadcast("rate", store.last);
export let getRates = async () => {
connect();
- let date = 0, fx;
+ let date = 0,
+ fx;
let rates = await g("rates");
if (rates) ({ date, fx } = rates);
diff --git a/lib/sendInternal.js b/lib/sendInternal.js
index 0ba0f0b4..32e94aa2 100644
--- a/lib/sendInternal.js
+++ b/lib/sendInternal.js
@@ -11,10 +11,7 @@ import { g, s, db } from "$lib/db";
const { HOSTNAME: hostname } = process.env;
-export default async (
- { amount, hash, memo, tip },
- user
-) => {
+export default async ({ amount, hash, memo, tip }, user) => {
amount = parseInt(amount);
if (!amount || amount < 0) fail("Amount must be greater than zero");
diff --git a/lib/sockets.js b/lib/sockets.js
index 7f655570..e803d5b0 100644
--- a/lib/sockets.js
+++ b/lib/sockets.js
@@ -47,7 +47,6 @@ export const broadcast = (type, data) => {
});
};
-
export async function socketServer(app) {
let seconds = (n, d = new Date()) => d.setSeconds(d.getSeconds() - n) && d;
@@ -90,9 +89,7 @@ export async function socketServer(app) {
const existing = Object.keys(store.sockets[uid]);
if (existing.length > 4) {
const p = existing.find(sid => sid !== uid);
- store.sockets[uid][p].send(
- JSON.stringify({ type: "logout" })
- );
+ store.sockets[uid][p].send(JSON.stringify({ type: "logout" }));
setTimeout(() => {
if (store.sockets[uid][p])
store.sockets[uid][p].close(code, "too many sockets");
@@ -149,7 +146,6 @@ export async function socketServer(app) {
});
}
-
export let sendHeartbeat = () => {
for (const uid in store.sockets) {
for (const id in store.sockets[uid]) {
@@ -158,4 +154,4 @@ export let sendHeartbeat = () => {
if (ws.beats > 10) ws.close(code, `${uid} ${id} lost heartbeat`);
}
}
-}
+};
diff --git a/lib/upload.js b/lib/upload.js
index b37e0bf2..43cc35ce 100644
--- a/lib/upload.js
+++ b/lib/upload.js
@@ -8,37 +8,36 @@ import { pipeline } from "stream";
import { g, s } from "$lib/db";
export default async ({ params: { type }, file, user }, res) => {
- if (!["banner", "profile"].includes(type))
- throw new Error("invalid upload");
+ if (!["banner", "profile"].includes(type)) throw new Error("invalid upload");
- let data = await file();
- let s1 = new Clone(data.file);
- let s2 = new Clone(data.file);
+ let data = await file();
+ let s1 = new Clone(data.file);
+ let s2 = new Clone(data.file);
- let [format, ext] = (await fileTypeFromStream(s1)).mime.split("/");
+ let [format, ext] = (await fileTypeFromStream(s1)).mime.split("/");
- if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext))
- throw new Error("unsupported file type");
+ if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext))
+ throw new Error("unsupported file type");
- let name = `${user.id}-${type}.webp`;
- let path = `/app/uploads/${name}`;
- let size = type === "banner" ? 1920 : 240;
+ let name = `${user.id}-${type}.webp`;
+ let path = `/app/uploads/${name}`;
+ let size = type === "banner" ? 1920 : 240;
- let t = sharp()
- .rotate()
- .resize(size)
- .webp();
+ let t = sharp()
+ .rotate()
+ .resize(size)
+ .webp();
- await new Promise(r => pipeline(s2, t, fs.createWriteStream(path), r));
+ await new Promise(r => pipeline(s2, t, fs.createWriteStream(path), r));
- let r = async () => {
- await db.watch(`user:${user.id}`);
- user = await g(`user:${user.id}`);
- user[type] = true;
- let m = await db.multi();
- await s(`user:${user.id}`, user);
- };
- await r();
+ let r = async () => {
+ await db.watch(`user:${user.id}`);
+ user = await g(`user:${user.id}`);
+ user[type] = true;
+ let m = await db.multi();
+ await s(`user:${user.id}`, user);
+ };
+ await r();
- res.send(name);
-}
+ res.send(name);
+};
diff --git a/routes/events.js b/routes/events.js
index cea82118..21ee37d8 100644
--- a/routes/events.js
+++ b/routes/events.js
@@ -4,4 +4,3 @@ import redis from "$lib/db";
import { coinos, pool, q } from "$lib/nostr";
import store from "$lib/store";
import { nada, wait } from "$lib/utils";
-
diff --git a/routes/locations.js b/routes/locations.js
index e080a7b9..fb4487f7 100644
--- a/routes/locations.js
+++ b/routes/locations.js
@@ -1,7 +1,7 @@
import { g } from "$lib/db";
export default {
-async list(req, res) {
- res.send({ locations: await g('locations') });
-}
-}
+ async list(req, res) {
+ res.send({ locations: await g("locations") });
+ }
+};
diff --git a/routes/nostr.js b/routes/nostr.js
index 3d326e94..35b40c07 100644
--- a/routes/nostr.js
+++ b/routes/nostr.js
@@ -1,9 +1,14 @@
+import { nada, uniq } from "$lib/utils";
+import config from "$config";
+import { g, s, db } from "$lib/db";
+import { q } from "$lib/nostr";
+
export default {
async event({ params: { id } }, res) {
- let event = JSON.parse(await g(`ev:${id}`));
+ let event = await g(`ev:${id}`);
let { pubkey } = event;
- event.user = JSON.parse(await g(`user:${pubkey}`)) || {
+ event.user = (await g(`user:${pubkey}`)) || {
username: pubkey.substr(0, 6),
pubkey,
anon: true,
@@ -15,13 +20,7 @@ export default {
},
async notes({ params: { pubkey } }, res) {
- let user = JSON.parse(await g(`user:${pubkey}`));
-
- if (!user) {
- user = await db.User.findOne({
- where: { pubkey }
- });
- }
+ let user = await g(`user:${pubkey}`);
if (!user)
user = {
@@ -40,7 +39,7 @@ export default {
q(`${pubkey}:notes`, params, opts).catch(nada);
- await g(`user:${pubkey}`, JSON.stringify(user));
+ await s(`user:${pubkey}`, user);
let ids = await db.sMembers(pubkey);
@@ -57,7 +56,7 @@ export default {
res.send(event);
},
- async follows({ params: { pubkey }, query: { tagsOnly } }, res) {
+ async follows({ params: { pubkey }, query: { tagsonly } }, res) {
let sub = `${pubkey}:follows`,
params = {
limit: 1,
@@ -68,7 +67,7 @@ export default {
q(sub, params, opts).catch(nada);
- let tags = JSON.parse(await g(`${pubkey}:follows`)) || [];
+ let tags = (await g(`${pubkey}:follows`)) || [];
if (tagsonly) return res.send(tags);
let follows = [];
@@ -81,7 +80,7 @@ export default {
authors: [pubkey]
}).catch(nada);
- let user = JSON.parse(await g(`user:${pubkey}`));
+ let user = await g(`user:${pubkey}`);
if (!user)
user = {
@@ -99,11 +98,10 @@ export default {
res.send(follows);
},
- async followers({ params: { pubkey}}, res) {
+ async followers({ params: { pubkey } }, res) {
try {
let pubkeys = [
...new Set([
- ...(await got(`${config.nostr}/followers?pubkey=${pubkey}`).json()),
...(await db.sMembers(`${pubkey}:followers`))
])
];
@@ -117,7 +115,7 @@ export default {
).catch(nada);
for (let pubkey of pubkeys) {
- let user = JSON.parse(await g(`user:${pubkey}`));
+ let user = await g(`user:${pubkey}`);
if (!user || !user.updated) {
q(`${pubkey}:profile:f2`, {
limit: 1,
@@ -125,7 +123,7 @@ export default {
authors: [pubkey]
}).catch(nada);
- user = JSON.parse(await g(`user:${pubkey}`));
+ user = await g(`user:${pubkey}`);
}
if (!user)
diff --git a/routes/send.js b/routes/send.js
index 1bd4910a..4b954616 100644
--- a/routes/send.js
+++ b/routes/send.js
@@ -8,7 +8,7 @@ export default async (req, res, next) => {
let payment = await sendInternal(req.body, req.user);
res.send(payment);
} catch (e) {
- console.log(e)
+ console.log(e);
err("problem sending internal payment", e.message);
return res.code(500).send(e.message);
}
diff --git a/sampleconfig/index.js b/sampleconfig/index.js
index 8683bfa6..8fcb0a6f 100644
--- a/sampleconfig/index.js
+++ b/sampleconfig/index.js
@@ -10,7 +10,7 @@ export default {
username: "admin1",
password: "123",
network: "regtest",
- port: 18443,
+ port: 18443
},
lightning: "/app/config/lightning/regtest/lightning-rpc"
};