Use PublicKeyHex instead of PublicKey where we can

This commit is contained in:
Mike Dilger 2022-12-31 15:25:04 +13:00
parent a6bb675f83
commit 72b086d48d
7 changed files with 59 additions and 73 deletions

View File

@ -57,7 +57,6 @@ pub struct Globals {
pub desired_events: RwLock<HashMap<Id, Vec<Url>>>, pub desired_events: RwLock<HashMap<Id, Vec<Url>>>,
/// All nostr people records currently loaded into memory, keyed by pubkey /// All nostr people records currently loaded into memory, keyed by pubkey
//pub people: RwLock<HashMap<PublicKey, DbPerson>>,
pub people: RwLock<People>, pub people: RwLock<People>,
/// All nostr relay records we have /// All nostr relay records we have

View File

@ -174,7 +174,7 @@ impl Overlord {
.get_followed_pubkeys() .get_followed_pubkeys()
.await .await
.iter() .iter()
.map(|p| PublicKeyHex::from(*p)) .map(|p| p.to_owned())
.collect(); .collect();
let (num_relays_per_person, max_relays) = { let (num_relays_per_person, max_relays) = {
@ -593,7 +593,7 @@ impl Overlord {
.write() .write()
.await .await
.upsert_valid_nip05( .upsert_valid_nip05(
(*pubkey).into(), &(*pubkey).into(),
dns_id.clone(), dns_id.clone(),
Unixtime::now().unwrap().0 as u64, Unixtime::now().unwrap().0 as u64,
) )
@ -604,7 +604,7 @@ impl Overlord {
.people .people
.write() .write()
.await .await
.follow((*pubkey).into()) .follow(&(*pubkey).into())
.await?; .await?;
info!("Followed {}", &dns_id); info!("Followed {}", &dns_id);
@ -639,7 +639,7 @@ impl Overlord {
async fn follow_bech32(bech32: String, relay: String) -> Result<(), Error> { async fn follow_bech32(bech32: String, relay: String) -> Result<(), Error> {
let pk = PublicKey::try_from_bech32_string(&bech32)?; let pk = PublicKey::try_from_bech32_string(&bech32)?;
let pkhex: PublicKeyHex = pk.into(); let pkhex: PublicKeyHex = pk.into();
GLOBALS.people.write().await.follow(pkhex.clone()).await?; GLOBALS.people.write().await.follow(&pkhex).await?;
debug!("Followed {}", &pkhex); debug!("Followed {}", &pkhex);
@ -667,7 +667,7 @@ impl Overlord {
async fn follow_hexkey(hexkey: String, relay: String) -> Result<(), Error> { async fn follow_hexkey(hexkey: String, relay: String) -> Result<(), Error> {
let pk = PublicKey::try_from_hex_string(&hexkey)?; let pk = PublicKey::try_from_hex_string(&hexkey)?;
let pkhex: PublicKeyHex = pk.into(); let pkhex: PublicKeyHex = pk.into();
GLOBALS.people.write().await.follow(pkhex.clone()).await?; GLOBALS.people.write().await.follow(&pkhex).await?;
debug!("Followed {}", &pkhex); debug!("Followed {}", &pkhex);

View File

@ -1,14 +1,14 @@
use crate::db::DbPerson; use crate::db::DbPerson;
use crate::error::Error; use crate::error::Error;
use crate::globals::GLOBALS; use crate::globals::GLOBALS;
use nostr_types::{Metadata, PublicKey, PublicKeyHex, Unixtime}; use nostr_types::{Metadata, PublicKeyHex, Unixtime};
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use tokio::task; use tokio::task;
pub struct People { pub struct People {
people: HashMap<PublicKey, DbPerson>, people: HashMap<PublicKeyHex, DbPerson>,
deferred_load: HashSet<PublicKey>, deferred_load: HashSet<PublicKeyHex>,
} }
impl People { impl People {
@ -19,31 +19,29 @@ impl People {
} }
} }
pub async fn get_followed_pubkeys(&self) -> Vec<PublicKey> { pub async fn get_followed_pubkeys(&self) -> Vec<PublicKeyHex> {
let mut output: Vec<PublicKey> = Vec::new(); let mut output: Vec<PublicKeyHex> = Vec::new();
for (_, person) in self.people.iter() { for (_, person) in self.people.iter() {
if let Ok(pubkey) = PublicKey::try_from_hex_string(&person.pubkey.0) { output.push(person.pubkey.clone());
output.push(pubkey);
}
} }
output output
} }
pub async fn create_if_missing(&mut self, pubkey: PublicKey) -> Result<(), Error> { pub async fn create_if_missing(&mut self, pubkeyhex: &PublicKeyHex) -> Result<(), Error> {
if self.people.contains_key(&pubkey) { if self.people.contains_key(pubkeyhex) {
return Ok(()); return Ok(());
} }
// Try loading from the database // Try loading from the database
let maybe_dbperson = Self::fetch_one(pubkey.into()).await?; let maybe_dbperson = Self::fetch_one(pubkeyhex).await?;
if let Some(dbperson) = maybe_dbperson { if let Some(dbperson) = maybe_dbperson {
// Insert into the map // Insert into the map
self.people.insert(pubkey, dbperson); self.people.insert(pubkeyhex.to_owned(), dbperson);
} else { } else {
// Create new // Create new
let dbperson = DbPerson { let dbperson = DbPerson {
pubkey: pubkey.into(), pubkey: pubkeyhex.to_owned(),
name: None, name: None,
about: None, about: None,
picture: None, picture: None,
@ -54,7 +52,7 @@ impl People {
followed: 0, followed: 0,
}; };
// Insert into the map // Insert into the map
self.people.insert(pubkey, dbperson.clone()); self.people.insert(pubkeyhex.to_owned(), dbperson.clone());
// Insert into the database // Insert into the database
Self::insert(dbperson).await?; Self::insert(dbperson).await?;
} }
@ -64,15 +62,15 @@ impl People {
pub async fn update_metadata( pub async fn update_metadata(
&mut self, &mut self,
pubkey: PublicKey, pubkeyhex: &PublicKeyHex,
metadata: Metadata, metadata: Metadata,
asof: Unixtime, asof: Unixtime,
) -> Result<(), Error> { ) -> Result<(), Error> {
// Sync in from database first // Sync in from database first
self.create_if_missing(pubkey).await?; self.create_if_missing(pubkeyhex).await?;
// Update the map // Update the map
let person = self.people.get_mut(&pubkey).unwrap(); let person = self.people.get_mut(pubkeyhex).unwrap();
if let Some(metadata_at) = person.metadata_at { if let Some(metadata_at) = person.metadata_at {
if asof.0 <= metadata_at { if asof.0 <= metadata_at {
// Old metadata. Ignore it // Old metadata. Ignore it
@ -91,7 +89,7 @@ impl People {
// Update the database // Update the database
let person = person.clone(); let person = person.clone();
let pubkeyhex: PublicKeyHex = person.pubkey.clone(); let pubkeyhex2 = pubkeyhex.to_owned();
task::spawn_blocking(move || { task::spawn_blocking(move || {
let maybe_db = GLOBALS.db.blocking_lock(); let maybe_db = GLOBALS.db.blocking_lock();
let db = maybe_db.as_ref().unwrap(); let db = maybe_db.as_ref().unwrap();
@ -105,7 +103,7 @@ impl People {
&person.picture, &person.picture,
&person.dns_id, &person.dns_id,
&person.metadata_at, &person.metadata_at,
&pubkeyhex.0, &pubkeyhex2.0,
))?; ))?;
Ok::<(), Error>(()) Ok::<(), Error>(())
}) })
@ -154,21 +152,19 @@ impl People {
.await?; .await?;
for person in output? { for person in output? {
if let Ok(pubkey) = PublicKey::try_from_hex_string(&person.pubkey.0) { self.people.insert(person.pubkey.clone(), person);
self.people.insert(pubkey, person);
}
} }
Ok(()) Ok(())
} }
pub fn get(&mut self, pubkey: PublicKey) -> Option<DbPerson> { pub fn get(&mut self, pubkeyhex: &PublicKeyHex) -> Option<DbPerson> {
if self.people.contains_key(&pubkey) { if self.people.contains_key(pubkeyhex) {
self.people.get(&pubkey).cloned() self.people.get(pubkeyhex).cloned()
} else { } else {
// Not there. Maybe it's in the database. Defer and let syncer // Not there. Maybe it's in the database. Defer and let syncer
// try to load // try to load
self.deferred_load.insert(pubkey); self.deferred_load.insert(pubkeyhex.to_owned());
let _ = GLOBALS.to_syncer.send("sync_people".to_owned()); let _ = GLOBALS.to_syncer.send("sync_people".to_owned());
None None
} }
@ -188,10 +184,10 @@ impl People {
} }
pub async fn sync(&mut self) -> Result<(), Error> { pub async fn sync(&mut self) -> Result<(), Error> {
for pubkey in self.deferred_load.iter() { for pubkeyhex in self.deferred_load.iter() {
if !self.people.contains_key(pubkey) { if !self.people.contains_key(pubkeyhex) {
if let Some(person) = Self::fetch_one((*pubkey).into()).await? { if let Some(person) = Self::fetch_one(pubkeyhex).await? {
let _ = self.people.insert(*pubkey, person); let _ = self.people.insert(pubkeyhex.to_owned(), person);
} }
} }
} }
@ -214,11 +210,11 @@ impl People {
Ok(()) Ok(())
} }
pub async fn follow(&mut self, pubkeyhex: PublicKeyHex) -> Result<(), Error> { pub async fn follow(&mut self, pubkeyhex: &PublicKeyHex) -> Result<(), Error> {
// Follow in database // Follow in database
let sql = "INSERT INTO PERSON (pubkey, followed) values (?, 1) \ let sql = "INSERT INTO PERSON (pubkey, followed) values (?, 1) \
ON CONFLICT(pubkey) DO UPDATE SET followed=1"; ON CONFLICT(pubkey) DO UPDATE SET followed=1";
let pubkeyhex2 = pubkeyhex.clone(); let pubkeyhex2 = pubkeyhex.to_owned();
task::spawn_blocking(move || { task::spawn_blocking(move || {
let maybe_db = GLOBALS.db.blocking_lock(); let maybe_db = GLOBALS.db.blocking_lock();
let db = maybe_db.as_ref().unwrap(); let db = maybe_db.as_ref().unwrap();
@ -229,13 +225,12 @@ impl People {
.await??; .await??;
// Make sure memory matches // Make sure memory matches
let pubkey: PublicKey = PublicKey::try_from_hex_string(&pubkeyhex.0)?; if let Some(dbperson) = self.people.get_mut(pubkeyhex) {
if let Some(dbperson) = self.people.get_mut(&pubkey) {
dbperson.followed = 1; dbperson.followed = 1;
} else { } else {
// load // load
if let Some(person) = Self::fetch_one(pubkeyhex).await? { if let Some(person) = Self::fetch_one(pubkeyhex).await? {
self.people.insert(pubkey, person); self.people.insert(pubkeyhex.to_owned(), person);
} }
} }
@ -244,13 +239,12 @@ impl People {
pub async fn upsert_valid_nip05( pub async fn upsert_valid_nip05(
&mut self, &mut self,
pubkeyhex: PublicKeyHex, pubkeyhex: &PublicKeyHex,
dns_id: String, dns_id: String,
dns_id_last_checked: u64, dns_id_last_checked: u64,
) -> Result<(), Error> { ) -> Result<(), Error> {
// Update memory // Update memory
let pubkey: PublicKey = PublicKey::try_from_hex_string(&pubkeyhex.0)?; if let Some(dbperson) = self.people.get_mut(pubkeyhex) {
if let Some(dbperson) = self.people.get_mut(&pubkey) {
dbperson.dns_id = Some(dns_id.clone()); dbperson.dns_id = Some(dns_id.clone());
dbperson.dns_id_last_checked = Some(dns_id_last_checked); dbperson.dns_id_last_checked = Some(dns_id_last_checked);
} }
@ -260,13 +254,14 @@ impl People {
values (?, ?, 1, ?) \ values (?, ?, 1, ?) \
ON CONFLICT(pubkey) DO UPDATE SET dns_id=?, dns_id_valid=1, dns_id_last_checked=?"; ON CONFLICT(pubkey) DO UPDATE SET dns_id=?, dns_id_valid=1, dns_id_last_checked=?";
let pubkeyhex2 = pubkeyhex.to_owned();
task::spawn_blocking(move || { task::spawn_blocking(move || {
let maybe_db = GLOBALS.db.blocking_lock(); let maybe_db = GLOBALS.db.blocking_lock();
let db = maybe_db.as_ref().unwrap(); let db = maybe_db.as_ref().unwrap();
let mut stmt = db.prepare(sql)?; let mut stmt = db.prepare(sql)?;
stmt.execute(( stmt.execute((
&pubkeyhex.0, &pubkeyhex2.0,
&dns_id, &dns_id,
&dns_id_last_checked, &dns_id_last_checked,
&dns_id, &dns_id,
@ -317,8 +312,8 @@ impl People {
output output
} }
async fn fetch_one(pubkey: PublicKeyHex) -> Result<Option<DbPerson>, Error> { async fn fetch_one(pubkeyhex: &PublicKeyHex) -> Result<Option<DbPerson>, Error> {
let people = Self::fetch(Some(&format!("pubkey='{}'", pubkey))).await?; let people = Self::fetch(Some(&format!("pubkey='{}'", pubkeyhex))).await?;
if people.is_empty() { if people.is_empty() {
Ok(None) Ok(None)

View File

@ -47,7 +47,7 @@ pub async fn process_new_event(
.people .people
.write() .write()
.await .await
.create_if_missing(event.pubkey) .create_if_missing(&event.pubkey.into())
.await?; .await?;
// Update person_relay.last_fetched // Update person_relay.last_fetched
@ -227,7 +227,7 @@ pub async fn process_new_event(
.people .people
.write() .write()
.await .await
.update_metadata(event.pubkey, metadata, event.created_at) .update_metadata(&event.pubkey.into(), metadata, event.created_at)
.await?; .await?;
} }

View File

@ -7,7 +7,7 @@ use egui::{
Align, Color32, Context, Frame, Image, Label, Layout, RichText, ScrollArea, Sense, TextEdit, Align, Color32, Context, Frame, Image, Label, Layout, RichText, ScrollArea, Sense, TextEdit,
TextStyle, Ui, Vec2, TextStyle, Ui, Vec2,
}; };
use nostr_types::{EventKind, Id, PublicKey}; use nostr_types::{EventKind, Id, PublicKeyHex};
pub(super) fn update(app: &mut GossipUi, ctx: &Context, frame: &mut eframe::Frame, ui: &mut Ui) { pub(super) fn update(app: &mut GossipUi, ctx: &Context, frame: &mut eframe::Frame, ui: &mut Ui) {
let feed = GLOBALS.feed.blocking_lock().get(); let feed = GLOBALS.feed.blocking_lock().get();
@ -166,7 +166,7 @@ fn render_post(
return; return;
} }
let maybe_person = GLOBALS.people.blocking_write().get(event.pubkey); let maybe_person = GLOBALS.people.blocking_write().get(&event.pubkey.into());
let reactions = Globals::get_reactions_sync(event.id); let reactions = Globals::get_reactions_sync(event.id);
let replies = Globals::get_replies_sync(event.id); let replies = Globals::get_replies_sync(event.id);
@ -251,7 +251,7 @@ fn render_post(
) )
.clicked() .clicked()
{ {
set_person_view(app, event.pubkey); set_person_view(app, &event.pubkey.into());
}; };
// Everything else next // Everything else next
@ -338,15 +338,15 @@ fn render_post(
} }
} }
fn set_person_view(app: &mut GossipUi, pubkey: PublicKey) { fn set_person_view(app: &mut GossipUi, pubkeyhex: &PublicKeyHex) {
if let Some(dbperson) = GLOBALS.people.blocking_write().get(pubkey) { if let Some(dbperson) = GLOBALS.people.blocking_write().get(pubkeyhex) {
app.person_view_name = if let Some(name) = &dbperson.name { app.person_view_name = if let Some(name) = &dbperson.name {
Some(name.to_string()) Some(name.to_string())
} else { } else {
Some(GossipUi::pubkey_short(&pubkey)) Some(GossipUi::hex_pubkey_short(pubkeyhex))
}; };
app.person_view_person = Some(dbperson); app.person_view_person = Some(dbperson);
app.person_view_pubkey = Some(pubkey); app.person_view_pubkey = Some(pubkeyhex.to_owned());
app.page = Page::Person; app.page = Page::Person;
} }
} }

View File

@ -79,7 +79,7 @@ struct GossipUi {
import_hex: String, import_hex: String,
replying_to: Option<Id>, replying_to: Option<Id>,
hides: Vec<Id>, hides: Vec<Id>,
person_view_pubkey: Option<PublicKey>, person_view_pubkey: Option<PublicKeyHex>,
person_view_person: Option<DbPerson>, person_view_person: Option<DbPerson>,
person_view_name: Option<String>, person_view_name: Option<String>,
} }
@ -221,11 +221,6 @@ impl GossipUi {
) )
} }
pub fn pubkey_short(pubkey: &PublicKey) -> String {
let hex: PublicKeyHex = (*pubkey).into();
Self::hex_pubkey_short(&hex)
}
pub fn pubkey_long(pubkey: &PublicKey) -> String { pub fn pubkey_long(pubkey: &PublicKey) -> String {
let hex: PublicKeyHex = (*pubkey).into(); let hex: PublicKeyHex = (*pubkey).into();
hex.0 hex.0

View File

@ -4,7 +4,6 @@ use crate::db::DbPerson;
use crate::globals::GLOBALS; use crate::globals::GLOBALS;
use eframe::egui; use eframe::egui;
use egui::{Context, Image, RichText, ScrollArea, Sense, TextEdit, TopBottomPanel, Ui, Vec2}; use egui::{Context, Image, RichText, ScrollArea, Sense, TextEdit, TopBottomPanel, Ui, Vec2};
use nostr_types::PublicKey;
pub(super) fn update(app: &mut GossipUi, ctx: &Context, _frame: &mut eframe::Frame, ui: &mut Ui) { pub(super) fn update(app: &mut GossipUi, ctx: &Context, _frame: &mut eframe::Frame, ui: &mut Ui) {
TopBottomPanel::top("people_menu").show(ctx, |ui| { TopBottomPanel::top("people_menu").show(ctx, |ui| {
@ -188,14 +187,12 @@ pub(super) fn update(app: &mut GossipUi, ctx: &Context, _frame: &mut eframe::Fra
} }
fn set_person_view(app: &mut GossipUi, person: &DbPerson) { fn set_person_view(app: &mut GossipUi, person: &DbPerson) {
if let Ok(pk) = PublicKey::try_from_hex_string(&person.pubkey) { app.person_view_pubkey = Some(person.pubkey.clone());
app.person_view_pubkey = Some(pk); app.person_view_person = Some(person.clone());
app.person_view_person = Some(person.clone()); app.person_view_name = if let Some(name) = &person.name {
app.person_view_name = if let Some(name) = &person.name { Some(name.to_string())
Some(name.to_string()) } else {
} else { Some(GossipUi::hex_pubkey_short(&person.pubkey))
Some(GossipUi::pubkey_short(&pk)) };
}; app.page = Page::Person;
app.page = Page::Person;
}
} }