refactor: everything

This commit is contained in:
nullishamy 2025-04-11 12:29:29 +01:00
parent 90577e43b0
commit 022e6f9c6d
Signed by: amy
SSH key fingerprint: SHA256:WmV0uk6WgAQvDJlM8Ld4mFPHZo02CLXXP5VkwQ5xtyk
32 changed files with 1570 additions and 668 deletions

View file

@ -0,0 +1,14 @@
use rocket::{form::Form, post, serde::json::Json};
use crate::types::oauth::{App, CredentialApplication};
#[post("/apps", data = "<app>")]
pub async fn new_app(app: Form<App>) -> Json<CredentialApplication> {
Json(CredentialApplication {
name: app.client_name.clone(),
scopes: app.scopes.clone(),
redirect_uris: app.redirect_uris.clone(),
client_id: format!("id-for-{}", app.client_name),
client_secret: format!("secret-for-{}", app.client_name),
})
}

View file

@ -0,0 +1,62 @@
use rocket::{get, serde::json::Json};
use crate::types::instance::{Accounts, Configuration, Contact, Instance, MediaAttachments, Polls, Registrations, Statuses, Thumbnail, Translation, Urls};
#[get("/instance")]
pub async fn instance() -> Json<Instance> {
Json(Instance {
domain: "ferri.amy.mov".to_string(),
title: "Ferri".to_string(),
version: "0.0.1".to_string(),
source_url: "https://forge.amy.mov/amy/ferri".to_string(),
description: "ferriverse".to_string(),
thumbnail: Thumbnail {
url: "".to_string(),
},
icon: vec![],
languages: vec![],
configuration: Configuration {
urls: Urls {
streaming: "".to_string(),
about: "".to_string(),
privacy_policy: "".to_string(),
terms_of_service: "".to_string(),
},
accounts: Accounts {
max_featured_tags: 10,
max_pinned_statuses: 10,
},
statuses: Statuses {
max_characters: 1000,
max_media_attachments: 5,
characters_reserved_per_url: 10,
},
media_attachments: MediaAttachments {
supported_mime_types: vec![],
description_limit: 10,
image_size_limit: 10,
image_matrix_limit: 10,
video_size_limit: 10,
video_frame_rate_limit: 10,
video_matrix_limit: 10,
},
polls: Polls {
max_options: 10,
max_characters_per_option: 10,
min_expiration: 10,
max_expiration: 10,
},
translation: Translation { enabled: false },
},
registrations: Registrations {
enabled: false,
approval_required: true,
reason_required: true,
message: None,
min_age: 10,
},
contact: Contact {
email: "no".to_string(),
},
})
}

View file

@ -0,0 +1,5 @@
pub mod user;
pub mod apps;
pub mod instance;
pub mod status;
pub mod preferences;

View file

@ -0,0 +1,28 @@
use rocket::{get, serde::{json::Json, Deserialize, Serialize}};
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct Preferences {
#[serde(rename = "posting:default:visibility")]
pub posting_default_visibility: String,
#[serde(rename = "posting:default:sensitive")]
pub posting_default_sensitive: bool,
#[serde(rename = "posting:default:language")]
pub posting_default_language: Option<String>,
#[serde(rename = "reading:expand:media")]
pub reading_expand_media: String,
#[serde(rename = "reading:expand:spoilers")]
pub reading_expand_spoilers: bool,
}
#[get("/preferences")]
pub async fn preferences() -> Json<Preferences> {
Json(Preferences {
posting_default_visibility: "public".to_string(),
posting_default_sensitive: false,
posting_default_language: None,
reading_expand_media: "default".to_string(),
reading_expand_spoilers: false,
})
}

View file

@ -0,0 +1,40 @@
use rocket::{
FromForm,
form::Form,
post,
serde::{Deserialize, Serialize},
};
use rocket_db_pools::Connection;
use uuid::Uuid;
use main::ap;
use crate::{AuthenticatedUser, Db};
#[derive(Serialize, Deserialize, Debug, FromForm)]
#[serde(crate = "rocket::serde")]
pub struct Status {
status: String,
}
#[post("/statuses", data = "<status>")]
pub async fn new_status(mut db: Connection<Db>, status: Form<Status>, user: AuthenticatedUser) {
let user = ap::User::from_actor_id(&user.actor_id, &mut **db).await;
let post_id = Uuid::new_v4();
let uri = format!("https://ferri.amy.mov/users/{}/posts/{}", user.username(), post_id);
let id = user.id();
let post = sqlx::query!(
r#"
INSERT INTO post (id, user_id, content)
VALUES (?1, ?2, ?3)
RETURNING *
"#,
uri,
id,
status.status
)
.fetch_one(&mut **db)
.await
.unwrap();
dbg!(user, status, post);
}

View file

@ -0,0 +1,88 @@
use chrono::Local;
use main::ap;
use rocket::{
State, get, post,
serde::{Deserialize, Serialize, json::Json},
};
use rocket_db_pools::Connection;
use uuid::Uuid;
use crate::{AuthenticatedUser, Db, http::HttpClient};
#[derive(Debug, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct CredentialAcount {
pub id: String,
pub username: String,
pub acct: String,
pub display_name: String,
pub locked: bool,
pub bot: bool,
pub created_at: String,
pub attribution_domains: Vec<String>,
pub note: String,
pub url: String,
pub avatar: String,
pub avatar_static: String,
pub header: String,
pub header_static: String,
pub followers_count: i64,
pub following_count: i64,
pub statuses_count: i64,
pub last_status_at: String,
}
#[get("/accounts/verify_credentials")]
pub async fn verify_credentials() -> Json<CredentialAcount> {
Json(CredentialAcount {
id: "https://ferri.amy.mov/users/amy".to_string(),
username: "amy".to_string(),
acct: "amy@ferri.amy.mov".to_string(),
display_name: "amy".to_string(),
locked: false,
bot: false,
created_at: "2025-04-10T22:12:09Z".to_string(),
attribution_domains: vec![],
note: "".to_string(),
url: "https://ferri.amy.mov/@amy".to_string(),
avatar: "https://i.sstatic.net/l60Hf.png".to_string(),
avatar_static: "https://i.sstatic.net/l60Hf.png".to_string(),
header: "https://i.sstatic.net/l60Hf.png".to_string(),
header_static: "https://i.sstatic.net/l60Hf.png".to_string(),
followers_count: 1,
following_count: 1,
statuses_count: 1,
last_status_at: "2025-04-10T22:14:34Z".to_string(),
})
}
#[post("/accounts/<account>/follow")]
pub async fn new_follow(
mut db: Connection<Db>,
http: &State<HttpClient>,
account: &str,
user: AuthenticatedUser,
) {
let follower = ap::User::from_actor_id(&user.actor_id, &mut **db).await;
let followed = ap::User::from_username(account, &mut **db).await;
let outbox = ap::Outbox::for_user(follower.clone(), http.inner());
let activity = ap::Activity {
id: format!("https://ferri.amy.mov/activities/{}", Uuid::new_v4()),
ty: ap::ActivityType::Follow,
object: followed.actor_id().to_string(),
published: Local::now(),
};
let req = ap::OutgoingActivity {
signed_by: format!(
"https://ferri.amy.mov/users/{}#main-key",
follower.username()
),
req: activity,
to: followed.actor().clone(),
};
outbox.post(req).await;
}

View file

@ -0,0 +1,120 @@
use main::ap::http::HttpClient;
use rocket::{get, response::status, State};
use rocket_db_pools::Connection;
use uuid::Uuid;
use crate::{types::{self, activity, content, webfinger}, Db};
#[get("/finger/<account>")]
pub async fn finger_account(mut db: Connection<Db>, account: &str) -> status::Accepted<String> {
// user@host.com
let (name, host) = account.split_once("@").unwrap();
let user = resolve_user(name, host).await;
// Make actor
sqlx::query!(
r#"
INSERT INTO actor (id, inbox, outbox)
VALUES (?1, ?2, ?3)
ON CONFLICT(id) DO NOTHING
"#,
user.id,
user.inbox,
user.outbox
)
.execute(&mut **db)
.await
.unwrap();
let uuid = Uuid::new_v4().to_string();
let username = format!("{}@{}", user.name, host);
sqlx::query!(
r#"
INSERT INTO user (id, username, actor_id, display_name)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(id) DO NOTHING
"#,
uuid,
username,
user.id,
user.preferred_username
)
.execute(&mut **db)
.await
.unwrap();
status::Accepted(format!("https://ferri.amy.mov/users/{}", username))
}
pub async fn resolve_user(acct: &str, host: &str) -> types::Person {
let client = reqwest::Client::new();
let url = format!(
"https://{}/.well-known/webfinger?resource=acct:{}",
host, acct
);
let wf = client
.get(url)
.send()
.await
.unwrap()
.json::<webfinger::WebfingerResponse>()
.await
.unwrap();
let actor_link = wf
.links
.iter()
.find(|l| l.ty == Some("application/activity+json".to_string()))
.unwrap();
let href = actor_link.href.as_ref().unwrap();
client
.get(href)
.header("Accept", "application/activity+json")
.send()
.await
.unwrap()
.json::<types::Person>()
.await
.unwrap()
}
#[get("/test")]
pub async fn test(http: &State<HttpClient>) -> &'static str {
let user = resolve_user("amy@fedi.amy.mov", "fedi.amy.mov").await;
let post = activity::CreateActivity {
id: "https://ferri.amy.mov/activities/amy/20".to_string(),
ty: "Create".to_string(),
summary: "Amy create a note".to_string(),
actor: "https://ferri.amy.mov/users/amy".to_string(),
object: content::Post {
context: "https://www.w3.org/ns/activitystreams".to_string(),
id: "https://ferri.amy.mov/users/amy/posts/20".to_string(),
ty: "Note".to_string(),
content: "My first post".to_string(),
ts: "2025-04-10T10:48:11Z".to_string(),
to: vec!["https://ferri.amy.mov/users/amy/followers".to_string()],
cc: vec!["https://www.w3.org/ns/activitystreams#Public".to_string()],
},
ts: "2025-04-10T10:48:11Z".to_string(),
to: vec!["https://ferri.amy.mov/users/amy/followers".to_string()],
cc: vec![],
};
let key_id = "https://ferri.amy.mov/users/amy#main-key";
let follow = http
.post(user.inbox)
.json(&post)
.sign(key_id)
.activity()
.send()
.await.unwrap()
.text()
.await.unwrap();
dbg!(follow);
"Hello, world!"
}

View file

@ -0,0 +1,12 @@
use rocket::http::{ContentType, MediaType};
pub mod user;
pub mod oauth;
pub mod api;
pub mod well_known;
pub mod custom;
fn activity_type() -> ContentType {
ContentType(MediaType::new("application", "activity+json"))
}

View file

@ -0,0 +1,35 @@
use rocket::{get, post, response::Redirect, serde::{json::Json, Deserialize, Serialize}};
#[get("/oauth/authorize?<client_id>&<scope>&<redirect_uri>&<response_type>")]
pub async fn authorize(
client_id: &str,
scope: &str,
redirect_uri: &str,
response_type: &str,
) -> Redirect {
Redirect::temporary(format!(
"{}?code=code-for-{}&state=state-for-{}",
redirect_uri, client_id, client_id
))
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(crate = "rocket::serde")]
pub struct Token {
pub access_token: String,
pub token_type: String,
pub expires_in: i64,
pub scope: String,
pub id_token: String,
}
#[post("/oauth/token")]
pub async fn new_token() -> Json<Token> {
Json(Token {
access_token: "access-token".to_string(),
token_type: "Bearer".to_string(),
expires_in: 3600,
scope: "read write follow push".to_string(),
id_token: "id-token".to_string(),
})
}

View file

@ -0,0 +1,213 @@
use main::ap;
use rocket::{State, get, http::ContentType, post, serde::json::Json};
use rocket_db_pools::Connection;
use crate::{
Db,
http::HttpClient,
types::{OrderedCollection, Person, UserKey, activity, content},
};
use rocket::serde::json::serde_json;
use super::activity_type;
#[get("/users/<user>/inbox")]
pub async fn inbox(user: String) -> Json<OrderedCollection> {
Json(OrderedCollection {
ty: "OrderedCollection".to_string(),
summary: format!("Inbox for {}", user),
total_items: 0,
ordered_items: vec![],
})
}
#[post("/users/<user>/inbox", data = "<body>")]
pub async fn post_inbox(
mut db: Connection<Db>,
http: &State<HttpClient>,
user: String,
body: String,
) {
let min = serde_json::from_str::<activity::MinimalActivity>(&body).unwrap();
match min.ty.as_str() {
"Delete" => {
let activity = serde_json::from_str::<activity::DeleteActivity>(&body);
dbg!(activity.unwrap());
}
"Follow" => {
let activity = serde_json::from_str::<activity::FollowActivity>(&body).unwrap();
dbg!(&activity);
let user = http
.get(&activity.actor)
.activity()
.send()
.await
.unwrap()
.json::<Person>()
.await
.unwrap();
sqlx::query!(
r#"
INSERT INTO actor (id, inbox, outbox)
VALUES ( ?1, ?2, ?3 )
ON CONFLICT(id) DO NOTHING;
"#,
activity.actor,
user.inbox,
user.outbox
)
.execute(&mut **db)
.await
.unwrap();
sqlx::query!(
r#"
INSERT INTO follow (id, follower_id, followed_id)
VALUES ( ?1, ?2, ?3 )
ON CONFLICT(id) DO NOTHING;
"#,
activity.id,
activity.actor,
activity.object
)
.execute(&mut **db)
.await
.unwrap();
let accept = activity::AcceptActivity {
ty: "Accept".to_string(),
actor: "https://ferri.amy.mov/users/amy".to_string(),
object: activity.id,
};
let key_id = "https://ferri.amy.mov/users/amy#main-key";
let accept_res = http
.post(user.inbox)
.json(&accept)
.sign(key_id)
.activity()
.send()
.await
.unwrap()
.text()
.await
.unwrap();
dbg!(accept_res);
}
unknown => {
eprintln!("WARN: Unknown activity '{}' - {}", unknown, body);
}
}
dbg!(min);
println!("Body in inbox: {}", body);
}
#[get("/users/<user>/outbox")]
pub async fn outbox(user: String) -> Json<OrderedCollection> {
dbg!(&user);
Json(OrderedCollection {
ty: "OrderedCollection".to_string(),
summary: format!("Outbox for {}", user),
total_items: 0,
ordered_items: vec![],
})
}
#[get("/users/<user>/followers")]
pub async fn followers(mut db: Connection<Db>, user: String) -> Json<OrderedCollection> {
let target = ap::User::from_username(&user, &mut **db).await;
let actor_id = target.actor_id();
let followers = sqlx::query!(
r#"
SELECT follower_id FROM follow
WHERE followed_id = ?
"#,
actor_id
)
.fetch_all(&mut **db)
.await
.unwrap();
Json(OrderedCollection {
ty: "OrderedCollection".to_string(),
summary: format!("Followers for {}", user),
total_items: 1,
ordered_items: followers
.into_iter()
.map(|f| f.follower_id)
.collect::<Vec<_>>(),
})
}
#[get("/users/<user>/following")]
pub async fn following(mut db: Connection<Db>, user: String) -> Json<OrderedCollection> {
let target = ap::User::from_username(&user, &mut **db).await;
let actor_id = target.actor_id();
let following = sqlx::query!(
r#"
SELECT followed_id FROM follow
WHERE follower_id = ?
"#,
actor_id
)
.fetch_all(&mut **db)
.await
.unwrap();
Json(OrderedCollection {
ty: "OrderedCollection".to_string(),
summary: format!("Following for {}", user),
total_items: 1,
ordered_items: following
.into_iter()
.map(|f| f.followed_id)
.collect::<Vec<_>>(),
})
}
#[get("/users/<user>/posts/<post>")]
pub async fn post(user: String, post: String) -> (ContentType, Json<content::Post>) {
(
activity_type(),
Json(content::Post {
id: format!("https://ferri.amy.mov/users/{}/posts/{}", user, post),
context: "https://www.w3.org/ns/activitystreams".to_string(),
ty: "Note".to_string(),
content: "My first post".to_string(),
ts: "2025-04-10T10:48:11Z".to_string(),
to: vec!["https://ferri.amy.mov/users/amy/followers".to_string()],
cc: vec!["https://www.w3.org/ns/activitystreams#Public".to_string()],
}),
)
}
#[get("/users/<user>")]
pub async fn user(user: String) -> (ContentType, Json<Person>) {
(
activity_type(),
Json(Person {
context: "https://www.w3.org/ns/activitystreams".to_string(),
ty: "Person".to_string(),
id: format!("https://ferri.amy.mov/users/{}", user),
name: user.clone(),
preferred_username: user.clone(),
followers: format!("https://ferri.amy.mov/users/{}/followers", user),
following: format!("https://ferri.amy.mov/users/{}/following", user),
summary: format!("ferri {}", user),
inbox: format!("https://ferri.amy.mov/users/{}/inbox", user),
outbox: format!("https://ferri.amy.mov/users/{}/outbox", user),
public_key: Some(UserKey {
id: format!("https://ferri.amy.mov/users/{}#main-key", user),
owner: format!("https://ferri.amy.mov/users/{}", user),
public_key: include_str!("../../../public.pem").to_string(),
}),
}),
)
}

View file

@ -0,0 +1,44 @@
use main::ap;
use rocket::{get, serde::json::Json};
use rocket_db_pools::Connection;
use crate::{types::webfinger::{Link, WebfingerResponse}, Db};
#[get("/.well-known/host-meta")]
pub async fn host_meta() -> &'static str {
r#"
<?xml version="1.0" encoding="UTF-8"?>
<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
<Link rel="lrdd" template="https://ferri.amy.mov/.well-known/webfinger?resource={uri}"/>
</XRD>
"#
}
// https://mastodon.social/.well-known/webfinger?resource=acct:gargron@mastodon.social
#[get("/.well-known/webfinger?<resource>")]
pub async fn webfinger(mut db: Connection<Db>, resource: &str) -> Json<WebfingerResponse> {
println!("Webfinger request for {}", resource);
let acct = resource.strip_prefix("acct:").unwrap();
let (user, _) = acct.split_once("@").unwrap();
let user = ap::User::from_username(user, &mut **db).await;
Json(WebfingerResponse {
subject: resource.to_string(),
aliases: vec![
format!("https://ferri.amy.mov/users/{}", user.username()),
format!("https://ferri.amy.mov/@{}", user.username()),
],
links: vec![
Link {
rel: "http://webfinger.net/rel/profile-page".to_string(),
ty: Some("text/html".to_string()),
href: Some(format!("https://ferri.amy.mov/@{}", user.username())),
},
Link {
rel: "self".to_string(),
ty: Some("application/activity+json".to_string()),
href: Some(format!("https://ferri.amy.mov/users/{}", user.username())),
},
],
})
}