forked from lnbits/nostrrelay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crud.py
399 lines (316 loc) · 10.4 KB
/
crud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import json
from typing import List, Optional, Tuple
from . import db
from .models import NostrAccount
from .relay.event import NostrEvent
from .relay.filter import NostrFilter
from .relay.relay import NostrRelay, RelayPublicSpec, RelaySpec
########################## RELAYS ####################
async def create_relay(user_id: str, r: NostrRelay) -> NostrRelay:
await db.execute(
"""
INSERT INTO nostrrelay.relays (user_id, id, name, description, pubkey, contact, meta)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
user_id,
r.id,
r.name,
r.description,
r.pubkey,
r.contact,
json.dumps(dict(r.config)),
),
)
relay = await get_relay(user_id, r.id)
assert relay, "Created relay cannot be retrieved"
return relay
async def update_relay(user_id: str, r: NostrRelay) -> NostrRelay:
await db.execute(
"""
UPDATE nostrrelay.relays
SET (name, description, pubkey, contact, active, meta) = (?, ?, ?, ?, ?, ?)
WHERE user_id = ? AND id = ?
""",
(
r.name,
r.description,
r.pubkey,
r.contact,
r.active,
json.dumps(dict(r.config)),
user_id,
r.id,
),
)
return r
async def get_relay(user_id: str, relay_id: str) -> Optional[NostrRelay]:
row = await db.fetchone(
"""SELECT * FROM nostrrelay.relays WHERE user_id = ? AND id = ?""",
(
user_id,
relay_id,
),
)
return NostrRelay.from_row(row) if row else None
async def get_relay_by_id(relay_id: str) -> Optional[NostrRelay]:
"""Note: it does not require `user_id`. Can read any relay. Use it with care."""
row = await db.fetchone(
"""SELECT * FROM nostrrelay.relays WHERE id = ?""",
(relay_id,),
)
return NostrRelay.from_row(row) if row else None
async def get_relays(user_id: str) -> List[NostrRelay]:
rows = await db.fetchall(
"""SELECT * FROM nostrrelay.relays WHERE user_id = ? ORDER BY id ASC""",
(user_id,),
)
return [NostrRelay.from_row(row) for row in rows]
async def get_config_for_all_active_relays() -> dict:
rows = await db.fetchall(
"SELECT id, meta FROM nostrrelay.relays WHERE active = true",
)
active_relay_configs = {}
for r in rows:
active_relay_configs[r["id"]] = RelaySpec(
**json.loads(r["meta"])
) # todo: from_json
return active_relay_configs
async def get_public_relay(relay_id: str) -> Optional[dict]:
row = await db.fetchone(
"""SELECT * FROM nostrrelay.relays WHERE id = ?""", (relay_id,)
)
if not row:
return None
relay = NostrRelay.from_row(row)
return {
**NostrRelay.info(),
"id": relay.id,
"name": relay.name,
"description": relay.description,
"pubkey": relay.pubkey,
"contact": relay.contact,
"config": RelayPublicSpec(**dict(relay.config)).dict(by_alias=True),
}
async def delete_relay(user_id: str, relay_id: str):
await db.execute(
"""DELETE FROM nostrrelay.relays WHERE user_id = ? AND id = ?""",
(
user_id,
relay_id,
),
)
########################## EVENTS ####################
async def create_event(relay_id: str, e: NostrEvent, publisher: Optional[str]):
publisher = publisher if publisher else e.pubkey
await db.execute(
"""
INSERT INTO nostrrelay.events (
relay_id,
publisher,
id,
pubkey,
created_at,
kind,
content,
sig,
size
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (relay_id, id) DO NOTHING
""",
(
relay_id,
publisher,
e.id,
e.pubkey,
e.created_at,
e.kind,
e.content,
e.sig,
e.size_bytes,
),
)
# todo: optimize with bulk insert
for tag in e.tags:
name, value, *rest = tag
extra = json.dumps(rest) if rest else None
await create_event_tags(relay_id, e.id, name, value, extra)
async def get_events(
relay_id: str, filter: NostrFilter, include_tags=True
) -> List[NostrEvent]:
query, values = build_select_events_query(relay_id, filter)
rows = await db.fetchall(query, tuple(values))
events = []
for row in rows:
event = NostrEvent.from_row(row)
if include_tags:
event.tags = await get_event_tags(relay_id, event.id)
events.append(event)
return events
async def get_event(relay_id: str, id: str) -> Optional[NostrEvent]:
row = await db.fetchone(
"SELECT * FROM nostrrelay.events WHERE relay_id = ? AND id = ?",
(
relay_id,
id,
),
)
if not row:
return None
event = NostrEvent.from_row(row)
event.tags = await get_event_tags(relay_id, id)
return event
async def get_storage_for_public_key(relay_id: str, publisher_pubkey: str) -> int:
"""Returns the storage space in bytes for all the events of a public key. Deleted events are also counted"""
row = await db.fetchone(
"SELECT SUM(size) as sum FROM nostrrelay.events WHERE relay_id = ? AND publisher = ? GROUP BY publisher",
(
relay_id,
publisher_pubkey,
),
)
if not row:
return 0
return round(row["sum"])
async def get_prunable_events(relay_id: str, pubkey: str) -> List[Tuple[str, int]]:
"""Return the oldest 10 000 events. Only the `id` and the size are returned, so the data size should be small"""
query = """
SELECT id, size FROM nostrrelay.events
WHERE relay_id = ? AND pubkey = ?
ORDER BY created_at ASC LIMIT 10000
"""
rows = await db.fetchall(query, (relay_id, pubkey))
return [(r["id"], r["size"]) for r in rows]
async def mark_events_deleted(relay_id: str, filter: NostrFilter):
if filter.is_empty():
return None
_, where, values = filter.to_sql_components(relay_id)
await db.execute(
f"""UPDATE nostrrelay.events SET deleted=true WHERE {" AND ".join(where)}""",
tuple(values),
)
async def delete_events(relay_id: str, filter: NostrFilter):
if filter.is_empty():
return None
_, where, values = filter.to_sql_components(relay_id)
query = f"""DELETE from nostrrelay.events WHERE {" AND ".join(where)}"""
await db.execute(query, tuple(values))
# todo: delete tags
async def prune_old_events(relay_id: str, pubkey: str, space_to_regain: int):
prunable_events = await get_prunable_events(relay_id, pubkey)
prunable_event_ids = []
size = 0
for pe in prunable_events:
prunable_event_ids.append(pe[0])
size += pe[1]
if size > space_to_regain:
break
await delete_events(relay_id, NostrFilter(ids=prunable_event_ids))
async def delete_all_events(relay_id: str):
query = "DELETE from nostrrelay.events WHERE relay_id = ?"
await db.execute(query, (relay_id,))
# todo: delete tags
async def create_event_tags(
relay_id: str,
event_id: str,
tag_name: str,
tag_value: str,
extra_values: Optional[str],
):
await db.execute(
"""
INSERT INTO nostrrelay.event_tags (
relay_id,
event_id,
name,
value,
extra
)
VALUES (?, ?, ?, ?, ?)
""",
(relay_id, event_id, tag_name, tag_value, extra_values),
)
async def get_event_tags(relay_id: str, event_id: str) -> List[List[str]]:
rows = await db.fetchall(
"SELECT * FROM nostrrelay.event_tags WHERE relay_id = ? and event_id = ?",
(relay_id, event_id),
)
tags: List[List[str]] = []
for row in rows:
tag = [row["name"], row["value"]]
extra = row["extra"]
if extra:
tag += json.loads(extra)
tags.append(tag)
return tags
def build_select_events_query(relay_id: str, filter: NostrFilter):
inner_joins, where, values = filter.to_sql_components(relay_id)
query = f"""
SELECT id, pubkey, created_at, kind, content, sig
FROM nostrrelay.events
{" ".join(inner_joins)}
WHERE { " AND ".join(where)}
ORDER BY created_at DESC
"""
# todo: check & enforce range
if filter.limit and filter.limit > 0:
query += f" LIMIT {filter.limit}"
return query, values
########################## ACCOUNTS ####################
async def create_account(relay_id: str, a: NostrAccount) -> NostrAccount:
await db.execute(
"""
INSERT INTO nostrrelay.accounts (relay_id, pubkey, sats, storage, paid_to_join, allowed, blocked)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
relay_id,
a.pubkey,
a.sats,
a.storage,
a.paid_to_join,
a.allowed,
a.blocked,
),
)
account = await get_account(relay_id, a.pubkey)
assert account, "Created account cannot be retrieved"
return account
async def update_account(relay_id: str, a: NostrAccount) -> NostrAccount:
await db.execute(
"""
UPDATE nostrrelay.accounts
SET (sats, storage, paid_to_join, allowed, blocked) = (?, ?, ?, ?, ?)
WHERE relay_id = ? AND pubkey = ?
""",
(a.sats, a.storage, a.paid_to_join, a.allowed, a.blocked, relay_id, a.pubkey),
)
return a
async def delete_account(relay_id: str, pubkey: str):
await db.execute(
"""
DELETE FROM nostrrelay.accounts
WHERE relay_id = ? AND pubkey = ?
""",
(relay_id, pubkey),
)
async def get_account(
relay_id: str,
pubkey: str,
) -> Optional[NostrAccount]:
row = await db.fetchone(
"SELECT * FROM nostrrelay.accounts WHERE relay_id = ? AND pubkey = ?",
(relay_id, pubkey),
)
return NostrAccount.from_row(row) if row else None
async def get_accounts(
relay_id: str,
allowed=True,
blocked=False,
) -> List[NostrAccount]:
rows = await db.fetchall(
"SELECT * FROM nostrrelay.accounts WHERE relay_id = ? AND allowed = ? AND blocked = ?",
(relay_id, allowed, blocked),
)
return [NostrAccount.from_row(row) for row in rows]