Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Commit

Permalink
adds version create and project update
Browse files Browse the repository at this point in the history
  • Loading branch information
thesuzerain committed Nov 2, 2023
1 parent 9a00c2d commit 3edae49
Show file tree
Hide file tree
Showing 15 changed files with 367 additions and 44 deletions.
2 changes: 1 addition & 1 deletion src/auth/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl ValidateAuthorized for crate::database::models::OAuthClient {

pub async fn filter_authorized_versions(
versions: Vec<QueryVersion>,
user_option: &Option<User>,
user_option: Option<&User>,
pool: &web::Data<PgPool>,
) -> Result<Vec<crate::models::projects::Version>, ApiError> {
let mut return_versions = Vec::new();
Expand Down
2 changes: 2 additions & 0 deletions src/database/models/creator_follows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ use itertools::Itertools;
use super::{OrganizationId, UserId};
use crate::database::models::DatabaseError;

#[derive(Copy, Clone, Debug)]
pub struct UserFollow {
pub follower_id: UserId,
pub target_id: UserId,
}

#[derive(Copy, Clone, Debug)]
pub struct OrganizationFollow {
pub follower_id: UserId,
pub target_id: OrganizationId,
Expand Down
90 changes: 78 additions & 12 deletions src/database/models/event_item.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
dynamic::{DynamicId, IdType},
generate_event_id, DatabaseError, EventId, OrganizationId, ProjectId, UserId,
generate_event_id, DatabaseError, EventId, OrganizationId, ProjectId, UserId, VersionId,
};
use chrono::{DateTime, Utc};
use itertools::Itertools;
Expand All @@ -12,6 +12,8 @@ use std::convert::{TryFrom, TryInto};
#[sqlx(rename_all = "snake_case")]
pub enum EventType {
ProjectCreated,
VersionCreated,
ProjectUpdated,
}

impl PgHasArrayType for EventType {
Expand All @@ -20,18 +22,29 @@ impl PgHasArrayType for EventType {
}
}

#[derive(Debug)]
pub enum CreatorId {
User(UserId),
Organization(OrganizationId),
}

#[derive(Debug)]
pub enum EventData {
ProjectCreated {
project_id: ProjectId,
creator_id: CreatorId,
},
VersionCreated {
version_id: VersionId,
creator_id: CreatorId,
},
ProjectUpdated {
project_id: ProjectId,
updater_id: CreatorId,
},
}

#[derive(Debug)]
pub struct Event {
pub id: EventId,
pub event_data: EventData,
Expand Down Expand Up @@ -108,6 +121,40 @@ impl From<Event> for RawEvent {
created: None,
}
}
EventData::VersionCreated {
version_id,
creator_id,
} => {
let target_id = DynamicId::from(version_id);
let triggerer_id = DynamicId::from(creator_id);
RawEvent {
id: value.id,
target_id: target_id.id,
target_id_type: target_id.id_type,
triggerer_id: Some(triggerer_id.id),
triggerer_id_type: Some(triggerer_id.id_type),
event_type: EventType::VersionCreated,
metadata: None,
created: None,
}
}
EventData::ProjectUpdated {
project_id,
updater_id,
} => {
let target_id = DynamicId::from(project_id);
let triggerer_id = DynamicId::from(updater_id);
RawEvent {
id: value.id,
target_id: target_id.id,
target_id_type: target_id.id_type,
triggerer_id: Some(triggerer_id.id),
triggerer_id_type: Some(triggerer_id.id_type),
event_type: EventType::ProjectUpdated,
metadata: None,
created: None,
}
}
}
}
}
Expand All @@ -124,27 +171,46 @@ impl TryFrom<RawEvent> for Event {
(Some(id), Some(id_type)) => Some(DynamicId { id, id_type }),
_ => None,
};
Ok(match value.event_type {
EventType::ProjectCreated => Event {
id: value.id,
event_data: EventData::ProjectCreated {

let event = Event {
id : value.id,
event_data : match value.event_type {
EventType::ProjectCreated => EventData::ProjectCreated {
project_id: target_id.try_into()?,
creator_id: triggerer_id.map_or_else(|| {
Err(DatabaseError::UnexpectedNull(
"Neither triggerer_id nor triggerer_id_type should be null for project creation".to_string(),
))
}, |v| v.try_into())?,
},
time: value.created.map_or_else(
|| {
EventType::VersionCreated => EventData::VersionCreated {
version_id: target_id.try_into()?,
creator_id: triggerer_id.map_or_else(|| {
Err(DatabaseError::UnexpectedNull(
"the value of created should not be null".to_string(),
"Neither triggerer_id nor triggerer_id_type should be null for version creation".to_string(),
))
},
Ok,
)?,
}, |v| v.try_into())?,
},
EventType::ProjectUpdated => EventData::ProjectUpdated {
project_id: target_id.try_into()?,
updater_id: triggerer_id.map_or_else(|| {
Err(DatabaseError::UnexpectedNull(
"Neither triggerer_id nor triggerer_id_type should be null for project update".to_string(),
))
}, |v| v.try_into())?,
},
},
})
time : value.created.map_or_else(
|| {
Err(DatabaseError::UnexpectedNull(
"the value of created should not be null".to_string(),
))
},
Ok,
)?,
};

Ok(event)
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/database/models/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ pub mod dynamic {
ProjectId,
UserId,
OrganizationId,
VersionId,
}

impl PgHasArrayType for IdType {
Expand Down Expand Up @@ -506,6 +507,7 @@ pub mod dynamic {
}

from_static_impl!(ProjectId, IdType::ProjectId);
from_static_impl!(VersionId, IdType::VersionId);
from_static_impl!(UserId, IdType::UserId);
from_static_impl!(OrganizationId, IdType::OrganizationId);
}
13 changes: 12 additions & 1 deletion src/models/feeds.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::ids::Base62Id;
use super::ids::OrganizationId;
use super::users::UserId;
use crate::models::ids::ProjectId;
use crate::models::ids::{ProjectId, VersionId};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -34,6 +34,17 @@ pub enum FeedItemBody {
creator_id: CreatorId,
project_title: String,
},
ProjectUpdated {
project_id: ProjectId,
updater_id: CreatorId,
project_title: String,
},
VersionCreated {
project_id: ProjectId,
version_id: VersionId,
creator_id: CreatorId,
project_title: String,
},
}

impl From<crate::database::models::event_item::CreatorId> for CreatorId {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub async fn forge_updates(
.into_iter()
.filter(|x| x.loaders.iter().any(loaders))
.collect(),
&user_option,
user_option.as_ref(),
&pool,
)
.await?;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/v2/analytics_get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ async fn filter_allowed_ids(
.map(|id| Ok(VersionId(parse_base62(id)?).into()))
.collect::<Result<Vec<_>, ApiError>>()?;
let versions = version_item::Version::get_many(&ids, &***pool, redis).await?;
let ids: Vec<VersionId> = filter_authorized_versions(versions, &Some(user), pool)
let ids: Vec<VersionId> = filter_authorized_versions(versions, Some(&user), pool)
.await?
.into_iter()
.map(|x| x.id)
Expand Down
41 changes: 40 additions & 1 deletion src/routes/v2/projects.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::auth::{filter_authorized_projects, get_user_from_headers, is_authorized};
use crate::database;
use crate::database::models::image_item;
use crate::database::models::event_item::{CreatorId, EventData};
use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::project_item::{GalleryItem, ModCategory};
use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::database::models::{image_item, Event};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::models;
Expand All @@ -24,6 +25,7 @@ use crate::util::routes::read_from_payload;
use crate::util::validate::validation_errors_to_string;
use actix_web::{delete, get, patch, post, web, HttpRequest, HttpResponse};
use chrono::{DateTime, Utc};
use db_ids::OrganizationId;
use futures::TryStreamExt;
use meilisearch_sdk::indexes::IndexesResults;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -1118,6 +1120,14 @@ pub async fn project_edit(
)
.await?;

insert_project_update_event(
id.into(),
project_item.inner.organization_id,
&user,
&mut transaction,
)
.await?;

transaction.commit().await?;
Ok(HttpResponse::NoContent().body(""))
} else {
Expand Down Expand Up @@ -1467,6 +1477,14 @@ pub async fn projects_edit(
.await?;
}

insert_project_update_event(
project.inner.id.into(),
project.inner.organization_id,
&user,
&mut transaction,
)
.await?;

db_models::Project::clear_cache(project.inner.id, project.inner.slug, None, &redis).await?;
}

Expand Down Expand Up @@ -2558,3 +2576,24 @@ pub async fn delete_from_index(

Ok(())
}

async fn insert_project_update_event(
project_id: ProjectId,
organization_id: Option<OrganizationId>,
current_user: &crate::models::users::User,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), ApiError> {
let event = Event::new(
EventData::ProjectUpdated {
project_id: project_id.into(),
updater_id: organization_id.map_or_else(
|| CreatorId::User(current_user.id.into()),
CreatorId::Organization,
),
},
transaction,
)
.await?;
event.insert(transaction).await?;
Ok(())
}
33 changes: 32 additions & 1 deletion src/routes/v2/version_creation.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use super::project_creation::{CreateError, UploadedFile};
use crate::auth::get_user_from_headers;
use crate::database::models::event_item::{CreatorId, EventData};
use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::version_item::{
DependencyBuilder, VersionBuilder, VersionFileBuilder,
};
use crate::database::models::{self, image_item, Organization};
use crate::database::models::{self, image_item, Event, Organization};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::models::images::{Image, ImageContext, ImageId};
Expand Down Expand Up @@ -304,6 +305,14 @@ async fn version_create_inner(
})
.collect::<Vec<_>>();

insert_version_create_event(
version_id,
organization.map(|o| o.id),
&user,
transaction,
)
.await?;

version_builder = Some(VersionBuilder {
version_id: version_id.into(),
project_id,
Expand Down Expand Up @@ -961,3 +970,25 @@ pub fn get_name_ext(
};
Ok((file_name, file_extension))
}

async fn insert_version_create_event(
version_id: VersionId,
organization_id: Option<models::OrganizationId>,
current_user: &crate::models::users::User,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), CreateError> {
println!("Adding version create event");
let event = Event::new(
EventData::VersionCreated {
version_id: version_id.into(),
creator_id: organization_id.map_or_else(
|| CreatorId::User(current_user.id.into()),
CreatorId::Organization,
),
},
transaction,
)
.await?;
event.insert(transaction).await?;
Ok(())
}
2 changes: 1 addition & 1 deletion src/routes/v2/version_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ pub async fn get_versions_from_hashes(
let version_ids = files.iter().map(|x| x.version_id).collect::<Vec<_>>();
let versions_data = filter_authorized_versions(
database::models::Version::get_many(&version_ids, &**pool, &redis).await?,
&user_option,
user_option.as_ref(),
&pool,
)
.await?;
Expand Down
4 changes: 2 additions & 2 deletions src/routes/v2/versions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ pub async fn version_list(
response.sort();
response.dedup_by(|a, b| a.inner.id == b.inner.id);

let response = filter_authorized_versions(response, &user_option, &pool).await?;
let response = filter_authorized_versions(response, user_option.as_ref(), &pool).await?;

Ok(HttpResponse::Ok().json(response))
} else {
Expand Down Expand Up @@ -243,7 +243,7 @@ pub async fn versions_get(
.map(|x| x.1)
.ok();

let versions = filter_authorized_versions(versions_data, &user_option, &pool).await?;
let versions = filter_authorized_versions(versions_data, user_option.as_ref(), &pool).await?;

Ok(HttpResponse::Ok().json(versions))
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/v3/organizations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub async fn organization_unfollow(
ApiError::InvalidInput("The specified organization does not exist!".to_string())
})?;

DBOrganizationFollow::unfollow(current_user.id.into(), target.id.into(), &**pool).await?;
DBOrganizationFollow::unfollow(current_user.id.into(), target.id, &**pool).await?;

Ok(HttpResponse::NoContent().body(""))
}
Loading

0 comments on commit 3edae49

Please sign in to comment.