Skip to content

Commit

Permalink
[feat] db code?
Browse files Browse the repository at this point in the history
  • Loading branch information
CutestNekoAqua committed Apr 18, 2024
1 parent 8469b23 commit 4d4e3ed
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 92 deletions.
18 changes: 7 additions & 11 deletions src/activities/create_post.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
use crate::{
database::DatabaseHandle,
error::Error,
objects::post::DbPost,
objects::{person::DbUser, post::Note},
utils::generate_object_id,
database::StateHandle, entities::{post, user}, error::Error, objects::{person::DbUser, post::{DbPost, Note}}, utils::generate_object_id
};
use activitypub_federation::{
activity_sending::SendActivityTask,
Expand All @@ -19,7 +15,7 @@ use url::Url;
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreatePost {
pub(crate) actor: ObjectId<DbUser>,
pub(crate) actor: ObjectId<user::Model>,
#[serde(deserialize_with = "deserialize_one_or_many")]
pub(crate) to: Vec<Url>,
pub(crate) object: Note,
Expand All @@ -29,7 +25,7 @@ pub struct CreatePost {
}

impl CreatePost {
pub async fn send(note: Note, inbox: Url, data: &Data<DatabaseHandle>) -> Result<(), Error> {
pub async fn send(note: Note, inbox: Url, data: &Data<StateHandle>) -> Result<(), Error> {
print!("Sending reply to {}", &note.attributed_to);
let create = CreatePost {
actor: note.attributed_to.clone(),
Expand All @@ -40,7 +36,7 @@ impl CreatePost {
};
let create_with_context = WithContext::new_default(create);
let sends =
SendActivityTask::prepare(&create_with_context, &data.local_user(), vec![inbox], data)
SendActivityTask::prepare(&create_with_context, &data.local_user().await?, vec![inbox], data)
.await?;
for send in sends {
send.sign_and_send(data).await?;
Expand All @@ -51,7 +47,7 @@ impl CreatePost {

#[async_trait::async_trait]
impl ActivityHandler for CreatePost {
type DataType = DatabaseHandle;
type DataType = StateHandle;
type Error = crate::error::Error;

fn id(&self) -> &Url {
Expand All @@ -63,12 +59,12 @@ impl ActivityHandler for CreatePost {
}

async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
DbPost::verify(&self.object, &self.id, data).await?;
post::Model::verify(&self.object, &self.id, data).await?;
Ok(())
}

async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
DbPost::from_json(self.object, data).await?;
post::Model::from_json(self.object, data).await?;
Ok(())
}
}
29 changes: 20 additions & 9 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
use crate::{error::Error, objects::person::DbUser};
use crate::{entities::user, error::Error, objects::person::DbUser};
use anyhow::anyhow;
use sea_orm::{DatabaseConnection, EntityTrait};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use super::entities::prelude::User;

pub type DatabaseHandle = Arc<Database>;
#[derive(Debug, Clone)]
pub struct Config {}

#[derive(Debug, Clone)]
pub struct State {
pub database_connection: Arc<DatabaseConnection>,
pub config: Arc<Config>,
}

pub type StateHandle = Arc<State>;

/// Our "database" which contains all known users (local and federated)
#[derive(Debug)]
pub struct Database {
pub users: Mutex<Vec<DbUser>>,
}

impl Database {
pub fn local_user(&self) -> DbUser {
let lock = self.users.lock().unwrap();
lock.first().unwrap().clone()
impl State {
pub async fn local_user(&self) -> Result<user::Model, Error> {
let user = User::find().one(self.database_connection.as_ref()).await?.unwrap();
Ok(user.clone())
}

pub fn read_user(&self, name: &str) -> Result<DbUser, Error> {
let db_user = self.local_user();
if name == db_user.name {
pub async fn read_user(&self, name: &str) -> Result<user::Model, Error> {
let db_user = self.local_user().await?;
if name == db_user.username {
Ok(db_user)
} else {
Err(anyhow!("Invalid user {name}").into())
Expand Down
10 changes: 7 additions & 3 deletions src/entities/post.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use chrono::Utc;
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
Expand All @@ -10,9 +11,12 @@ pub struct Model {
pub title: Option<String>,
pub content: String,
pub local: bool,
pub created_at: String,
pub updated_at: Option<String>,
pub reblog_id: Option<String>,
#[sea_orm(column_type = "Timestamp")]
pub created_at: chrono::DateTime<Utc>,
#[sea_orm(column_type = "Timestamp")]
pub updated_at: Option<chrono::DateTime<Utc>>,
#[sea_orm(column_type = "Timestamp")]
pub reblog_id: Option<chrono::DateTime<Utc>>,
pub content_type: String,
pub visibility: String,
pub reply_id: Option<String>,
Expand Down
10 changes: 7 additions & 3 deletions src/entities/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use chrono::Utc;
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
Expand All @@ -13,12 +14,15 @@ pub struct Model {
pub url: String,
pub public_key: String,
pub private_key: Option<String>,
pub last_refreshed_at: String,
#[sea_orm(column_type = "Timestamp")]
pub last_refreshed_at: chrono::DateTime<Utc>,
pub local: bool,
pub follower_count: i32,
pub following_count: i32,
pub created_at: String,
pub updated_at: Option<String>,
#[sea_orm(column_type = "Timestamp")]
pub created_at: chrono::DateTime<Utc>,
#[sea_orm(column_type = "Timestamp")]
pub updated_at: Option<chrono::DateTime<Utc>>,
pub following: Option<String>,
pub followers: Option<String>,
pub inbox: String,
Expand Down
23 changes: 11 additions & 12 deletions src/http.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::{
database::DatabaseHandle,
error::Error,
objects::person::{DbUser, PersonAcceptedActivities},
database::StateHandle, entities::user, error::Error, objects::person::{DbUser, PersonAcceptedActivities}
};
use activitypub_federation::{
actix_web::{inbox::receive_activity, signing_actor},
Expand All @@ -15,8 +13,9 @@ use actix_web::{web, web::Bytes, App, HttpRequest, HttpResponse, HttpServer};
use anyhow::anyhow;
use serde::Deserialize;
use tracing::info;
use url::Url;

pub fn listen(config: &FederationConfig<DatabaseHandle>) -> Result<(), Error> {
pub fn listen(config: &FederationConfig<StateHandle>) -> Result<(), Error> {
let hostname = config.domain();
info!("Listening with actix-web on {hostname}");
let config = config.clone();
Expand Down Expand Up @@ -46,7 +45,7 @@ pub fn listen(config: &FederationConfig<DatabaseHandle>) -> Result<(), Error> {
pub async fn http_get_user(
request: HttpRequest,
user_name: web::Path<String>,
data: Data<DatabaseHandle>,
data: Data<StateHandle>,
) -> Result<HttpResponse, Error> {
//let signed_by = signing_actor::<DbUser>(&request, None, &data).await?;
// here, checks can be made on the actor or the domain to which
Expand All @@ -56,8 +55,8 @@ pub async fn http_get_user(
// signed_by.id()
//);

let db_user = data.local_user();
if user_name.into_inner() == db_user.name {
let db_user = data.local_user().await?;
if user_name.into_inner() == db_user.username {
let json_user = db_user.into_json(&data).await?;
Ok(HttpResponse::Ok()
.content_type(FEDERATION_CONTENT_TYPE)
Expand All @@ -71,9 +70,9 @@ pub async fn http_get_user(
pub async fn http_post_user_inbox(
request: HttpRequest,
body: Bytes,
data: Data<DatabaseHandle>,
data: Data<StateHandle>,
) -> Result<HttpResponse, Error> {
receive_activity::<WithContext<PersonAcceptedActivities>, DbUser, DatabaseHandle>(
receive_activity::<WithContext<PersonAcceptedActivities>, user::Model, StateHandle>(
request, body, &data,
)
.await
Expand All @@ -86,12 +85,12 @@ pub struct WebfingerQuery {

pub async fn webfinger(
query: web::Query<WebfingerQuery>,
data: Data<DatabaseHandle>,
data: Data<StateHandle>,
) -> Result<HttpResponse, Error> {
let name = extract_webfinger_name(&query.resource, &data)?;
let db_user = data.read_user(name)?;
let db_user = data.read_user(name).await?;
Ok(HttpResponse::Ok().json(build_webfinger_response(
query.resource.clone(),
db_user.ap_id.into_inner(),
Url::parse(&db_user.id)?,
)))
}
19 changes: 8 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use clap::Parser;
use database::Database;
use http::{http_get_user, http_post_user_inbox, webfinger};
use objects::person::DbUser;
use sea_orm::DatabaseConnection;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
Expand All @@ -15,6 +16,8 @@ use std::{
use tokio::signal;
use tracing::info;

use crate::database::{Config, State};

mod entities;
mod activities;
mod database;
Expand All @@ -23,15 +26,6 @@ mod http;
mod objects;
mod utils;

#[derive(Debug, Clone)]
struct Config {}

#[derive(Debug, Clone)]
struct State {
database: Arc<Database>,
config: Arc<Config>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Response {
health: bool,
Expand Down Expand Up @@ -63,6 +57,7 @@ async fn main() -> actix_web::Result<(), anyhow::Error> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

let server_url = env::var("LISTEN").unwrap_or("127.0.0.1:8080".to_string());
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");

let local_user = DbUser::new(
env::var("FEDERATED_DOMAIN")
Expand All @@ -78,16 +73,18 @@ async fn main() -> actix_web::Result<(), anyhow::Error> {
users: Mutex::new(vec![local_user]),
});

let db = sea_orm::Database::connect(database_url).await?;

let config = Config {};

let state: State = State {
database: new_database,
database_connection: db.into(),
config: Arc::new(config),
};

let data = FederationConfig::builder()
.domain(env::var("FEDERATED_DOMAIN").expect("FEDERATED_DOMAIN must be set"))
.app_data(state.clone().database)
.app_data(state.clone())
.build()
.await?;

Expand Down
Loading

0 comments on commit 4d4e3ed

Please sign in to comment.