lemmy/crates/db_schema/src/impls/site.rs

96 lines
2.6 KiB
Rust
Raw Normal View History

use crate::{
newtypes::{DbUrl, SiteId},
schema::site::dsl::{actor_id, id, site},
source::{
actor_language::SiteLanguage,
site::{Site, SiteInsertForm, SiteUpdateForm},
},
traits::Crud,
2022-11-09 10:05:00 +00:00
utils::{get_conn, DbPool},
};
use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
2022-11-09 10:05:00 +00:00
use diesel_async::RunQueryDsl;
use url::Url;
2022-11-09 10:05:00 +00:00
#[async_trait]
impl Crud for Site {
type InsertForm = SiteInsertForm;
type UpdateForm = SiteUpdateForm;
type IdType = SiteId;
/// Use SiteView::read_local, or Site::read_from_apub_id instead
async fn read(_pool: &DbPool, _site_id: SiteId) -> Result<Self, Error> {
unimplemented!()
2022-11-09 10:05:00 +00:00
}
2022-11-09 10:05:00 +00:00
async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
let conn = &mut get_conn(pool).await?;
let is_new_site = match &form.actor_id {
Some(id_) => Site::read_from_apub_id(pool, id_).await?.is_none(),
None => true,
};
// Can't do separate insert/update commands because InsertForm/UpdateForm aren't convertible
let site_ = insert_into(site)
.values(form)
.on_conflict(actor_id)
.do_update()
.set(form)
2022-11-09 10:05:00 +00:00
.get_result::<Self>(conn)
.await?;
// initialize languages if site is newly created
if is_new_site {
// initialize with all languages
SiteLanguage::update(pool, vec![], &site_).await?;
}
Ok(site_)
}
2022-11-09 10:05:00 +00:00
async fn update(
pool: &DbPool,
site_id: SiteId,
new_site: &Self::UpdateForm,
) -> Result<Self, Error> {
2022-11-09 10:05:00 +00:00
let conn = &mut get_conn(pool).await?;
diesel::update(site.find(site_id))
.set(new_site)
.get_result::<Self>(conn)
2022-11-09 10:05:00 +00:00
.await
}
2022-11-09 10:05:00 +00:00
async fn delete(pool: &DbPool, site_id: SiteId) -> Result<usize, Error> {
let conn = &mut get_conn(pool).await?;
diesel::delete(site.find(site_id)).execute(conn).await
2020-12-20 05:09:20 +00:00
}
}
2021-10-16 13:33:38 +00:00
impl Site {
pub async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result<Option<Self>, Error> {
2022-11-09 10:05:00 +00:00
let conn = &mut get_conn(pool).await?;
Ok(
site
.filter(actor_id.eq(object_id))
.first::<Site>(conn)
2022-11-09 10:05:00 +00:00
.await
.ok()
.map(Into::into),
)
}
// TODO this needs fixed
2022-11-09 10:05:00 +00:00
pub async fn read_remote_sites(pool: &DbPool) -> Result<Vec<Self>, Error> {
let conn = &mut get_conn(pool).await?;
site.order_by(id).offset(1).get_results::<Self>(conn).await
}
/// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
/// parts of the url.
pub fn instance_actor_id_from_url(mut url: Url) -> Url {
url.set_fragment(None);
url.set_path("");
url.set_query(None);
url
}
}