nostrdb: api: add ndb_note_json

add a way to write an ndb note as json to a buffer

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2024-04-30 23:19:05 +02:00
committed by Daniel D’Aquino
parent ffc50bb2c1
commit 92e1e4b08f
2 changed files with 51 additions and 0 deletions

View File

@@ -4726,6 +4726,54 @@ static int ndb_event_commitment(struct ndb_note *ev, unsigned char *buf, int buf
return cur.p - cur.start;
}
static int cursor_push_hex(struct cursor *c, unsigned char *bytes, int len)
{
int i;
unsigned char chr;
if (c->p + (len * 2) >= c->end)
return 0;
for (i = 0; i < len; i++) {
chr = bytes[i];
*(c->p++) = hexchar(chr >> 4);
*(c->p++) = hexchar(chr & 0xF);
}
return 1;
}
static int cursor_push_int_str(struct cursor *c, int num)
{
char timebuf[16] = {0};
snprintf(timebuf, sizeof(timebuf), "%d", num);
return cursor_push_str(c, timebuf);
}
int ndb_note_json(struct ndb_note *note, char *buf, int buflen)
{
struct cursor cur, *c = &cur;
make_cursor((unsigned char *)buf, (unsigned char*)buf + buflen, &cur);
return cursor_push_str(c, "{\"id\":\"") &&
cursor_push_hex(c, ndb_note_id(note), 32) &&
cursor_push_str(c, "\",\"pubkey\":\"") &&
cursor_push_hex(c, ndb_note_pubkey(note), 32) &&
cursor_push_str(c, "\",\"created_at\":") &&
cursor_push_int_str(c, ndb_note_created_at(note)) &&
cursor_push_str(c, ",\"kind\":") &&
cursor_push_int_str(c, ndb_note_kind(note)) &&
cursor_push_str(c, ",\"tags\":") &&
cursor_push_json_tags(c, note) &&
cursor_push_str(c, ",\"content\":") &&
cursor_push_jsonstr(c, ndb_note_content(note)) &&
cursor_push_str(c, ",\"sig\":\"") &&
cursor_push_hex(c, ndb_note_sig(note), 64) &&
cursor_push_c_str(c, "\"}");
}
int ndb_calculate_id(struct ndb_note *note, unsigned char *buf, int buflen) {
int len;

View File

@@ -532,6 +532,9 @@ void _ndb_note_set_kind(struct ndb_note *note, uint32_t kind);
struct ndb_tags *ndb_note_tags(struct ndb_note *note);
int ndb_str_len(struct ndb_str *str);
/// write the note as json to a buffer
int ndb_note_json(struct ndb_note *, char *buf, int buflen);
// TAGS
void ndb_tags_iterate_start(struct ndb_note *note, struct ndb_iterator *iter);
uint16_t ndb_tags_count(struct ndb_tags *);