lib.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use futures::future::join_all;
  2. use nostr_rs_client::Pool;
  3. use nostr_rs_relayer::Relayer;
  4. use nostr_rs_storage_base::Storage;
  5. use nostr_rs_types::types::{Addr, Filter, Id};
  6. use tokio::{net::TcpListener, task::JoinHandle};
  7. use url::Url;
  8. pub struct Stoppable(Option<Vec<JoinHandle<()>>>);
  9. impl From<Vec<JoinHandle<()>>> for Stoppable {
  10. fn from(value: Vec<JoinHandle<()>>) -> Self {
  11. Self(Some(value))
  12. }
  13. }
  14. impl Drop for Stoppable {
  15. fn drop(&mut self) {
  16. if let Some(tasks) = self.0.take() {
  17. for join_handle in tasks.into_iter() {
  18. join_handle.abort();
  19. }
  20. }
  21. }
  22. }
  23. #[derive(thiserror::Error, Debug)]
  24. pub enum Error {
  25. #[error("Relayer: {0}")]
  26. Relayer(#[from] nostr_rs_relayer::Error),
  27. #[error("Client error: {0}")]
  28. Client(#[from] nostr_rs_client::Error),
  29. }
  30. pub struct PersonalRelayer<T: Storage + Send + Sync + 'static> {
  31. relayer: Relayer<T>,
  32. accounts: Vec<Id>,
  33. }
  34. impl<T: Storage + Send + Sync + 'static> PersonalRelayer<T> {
  35. pub async fn new(storage: T, accounts: Vec<Id>, client_urls: Vec<Url>) -> Result<Self, Error> {
  36. let pool = Pool::new_with_clients(client_urls);
  37. join_all(
  38. accounts
  39. .iter()
  40. .map(|account| {
  41. pool.subscribe(
  42. Filter {
  43. authors: vec![account.clone()],
  44. ..Default::default()
  45. }
  46. .into(),
  47. )
  48. })
  49. .collect::<Vec<_>>(),
  50. )
  51. .await
  52. .into_iter()
  53. .collect::<Result<Vec<_>, _>>()?;
  54. Ok(Self {
  55. relayer: Relayer::new(Some(storage), Some(pool))?,
  56. accounts,
  57. })
  58. }
  59. pub fn main(self, server: TcpListener) -> Result<Stoppable, Error> {
  60. let (relayer, handle) = self.relayer.main(server)?;
  61. let tasks = vec![handle, tokio::spawn(async move {})];
  62. Ok(tasks.into())
  63. }
  64. }