Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Post scheduling (fixes #234) #5025

Merged
merged 26 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/api_common/src/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub struct CreatePost {
pub language_id: Option<LanguageId>,
/// Instead of fetching a thumbnail, use a custom one.
pub custom_thumbnail: Option<String>,
/// Time when this post should be scheduled. Null means publish immediately.
pub scheduled_publish_time: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -124,6 +126,8 @@ pub struct EditPost {
pub language_id: Option<LanguageId>,
/// Instead of fetching a thumbnail, use a custom one.
pub custom_thumbnail: Option<String>,
/// Time when this post should be scheduled. Null means publish immediately.
pub scheduled_publish_time: Option<i64>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq, Eq, Hash)]
Expand Down
2 changes: 1 addition & 1 deletion crates/api_common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ async fn check_community_deleted_removed(
Ok(())
}

async fn check_community_ban(
pub async fn check_community_ban(
person: &Person,
community_id: CommunityId,
pool: &mut DbPool<'_>,
Expand Down
1 change: 1 addition & 0 deletions crates/api_crud/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ futures.workspace = true
uuid = { workspace = true }
moka.workspace = true
anyhow.workspace = true
chrono.workspace = true
webmention = "0.6.0"
accept-language = "3.1.0"

Expand Down
23 changes: 17 additions & 6 deletions crates/api_crud/src/post/create.rs
Nutomic marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::convert_published_time;
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
Expand Down Expand Up @@ -130,6 +131,8 @@ pub async fn create_post(
}
};

let scheduled_publish_time =
convert_published_time(data.scheduled_publish_time, &local_user_view, &context).await?;
let post_form = PostInsertForm::builder()
.name(data.name.trim().to_string())
.url(url.map(Into::into))
Expand All @@ -139,16 +142,23 @@ pub async fn create_post(
.creator_id(local_user_view.person.id)
.nsfw(data.nsfw)
.language_id(language_id)
.scheduled_publish_time(scheduled_publish_time)
.build();

let inserted_post = Post::create(&mut context.pool(), &post_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntCreatePost)?;

let federate_post = if scheduled_publish_time.is_none() {
send_webmention(inserted_post.clone(), community);
|post| Some(SendActivityData::CreatePost(post))
} else {
|_| None
};
generate_post_link_metadata(
inserted_post.clone(),
custom_thumbnail.map(Into::into),
|post| Some(SendActivityData::CreatePost(post)),
federate_post,
context.reset_request_count(),
)
.await?;
Expand All @@ -168,11 +178,14 @@ pub async fn create_post(

mark_post_as_read(person_id, post_id, &mut context.pool()).await?;

if let Some(url) = inserted_post.url.clone() {
build_post_response(&context, community_id, local_user_view, post_id).await
}

pub fn send_webmention(post: Post, community: Community) {
if let Some(url) = post.url.clone() {
if community.visibility == CommunityVisibility::Public {
spawn_try_task(async move {
let mut webmention =
Webmention::new::<Url>(inserted_post.ap_id.clone().into(), url.clone().into())?;
let mut webmention = Webmention::new::<Url>(post.ap_id.clone().into(), url.clone().into())?;
webmention.set_checked(true);
match webmention
.send()
Expand All @@ -186,6 +199,4 @@ pub async fn create_post(
});
}
};

build_post_response(&context, community_id, local_user_view, post_id).await
}
33 changes: 33 additions & 0 deletions crates/api_crud/src/post/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
use chrono::{DateTime, TimeZone, Utc};
use lemmy_api_common::context::LemmyContext;
use lemmy_db_schema::source::post::Post;
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{error::LemmyResult, LemmyErrorType};

pub mod create;
pub mod delete;
pub mod read;
pub mod remove;
pub mod update;

async fn convert_published_time(
scheduled_publish_time: Option<i64>,
local_user_view: &LocalUserView,
context: &LemmyContext,
) -> LemmyResult<Option<DateTime<Utc>>> {
const MAX_SCHEDULED_POSTS: i64 = 10;
if let Some(scheduled_publish_time) = scheduled_publish_time {
let converted = Utc
.timestamp_opt(scheduled_publish_time, 0)
.single()
.ok_or(LemmyErrorType::InvalidUnixTime)?;
if converted < Utc::now() {
Err(LemmyErrorType::PostScheduleTimeMustBeInFuture)?;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be good to add an upper limit too? Up to you.

if !local_user_view.local_user.admin {
let count =
Post::user_scheduled_post_count(local_user_view.person.id, &mut context.pool()).await?;
if count >= MAX_SCHEDULED_POSTS {
Err(LemmyErrorType::TooManyScheduledPosts)?;
}
}
Ok(Some(converted))
} else {
Ok(None)
}
}
57 changes: 50 additions & 7 deletions crates/api_crud/src/post/update.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::{convert_published_time, create::send_webmention};
use activitypub_federation::config::Data;
use actix_web::web::Json;
use lemmy_api_common::{
Expand All @@ -16,6 +17,7 @@ use lemmy_api_common::{
use lemmy_db_schema::{
source::{
actor_language::CommunityLanguage,
community::Community,
local_site::LocalSite,
post::{Post, PostUpdateForm},
},
Expand Down Expand Up @@ -109,6 +111,21 @@ pub async fn update_post(
)
.await?;

// handle changes to scheduled_publish_time
let scheduled_publish_time = match (
orig_post.scheduled_publish_time,
data.scheduled_publish_time,
) {
// schedule time can be changed if post is still scheduled (and not published yet)
(Some(_), Some(_)) => {
Some(convert_published_time(data.scheduled_publish_time, &local_user_view, &context).await?)
}
// post was scheduled, gets changed to publish immediately
(Some(_), None) => Some(None),
// unchanged
(_, _) => None,
};

let post_form = PostUpdateForm {
name: data.name.clone(),
url,
Expand All @@ -117,6 +134,7 @@ pub async fn update_post(
nsfw: data.nsfw,
language_id: data.language_id,
updated: Some(Some(naive_now())),
scheduled_publish_time,
..Default::default()
};

Expand All @@ -125,13 +143,38 @@ pub async fn update_post(
.await
.with_lemmy_type(LemmyErrorType::CouldntUpdatePost)?;

generate_post_link_metadata(
updated_post.clone(),
custom_thumbnail.flatten().map(Into::into),
|post| Some(SendActivityData::UpdatePost(post)),
context.reset_request_count(),
)
.await?;
// send out federation/webmention if necessary
match (
orig_post.scheduled_publish_time,
data.scheduled_publish_time,
) {
// schedule was removed, send create activity and webmention
(Some(_), None) => {
let community = Community::read(&mut context.pool(), orig_post.community_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPost)?;
send_webmention(updated_post.clone(), community);
generate_post_link_metadata(
updated_post.clone(),
custom_thumbnail.flatten().map(Into::into),
|post| Some(SendActivityData::CreatePost(post)),
context.reset_request_count(),
)
.await?;
}
// post was already public, send update
(None, _) => {
generate_post_link_metadata(
updated_post.clone(),
custom_thumbnail.flatten().map(Into::into),
|post| Some(SendActivityData::UpdatePost(post)),
context.reset_request_count(),
)
.await?
}
// schedule was changed, do nothing
(Some(_), Some(_)) => {}
};

build_post_response(
context.deref(),
Expand Down
31 changes: 28 additions & 3 deletions crates/db_schema/src/impls/post.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
diesel::OptionalExtension,
diesel::{BoolExpressionMethods, OptionalExtension},
newtypes::{CommunityId, DbUrl, PersonId, PostId},
schema::{post, post_hide, post_like, post_read, post_saved},
schema::{community, person, post, post_hide, post_like, post_read, post_saved},
source::post::{
Post,
PostHide,
Expand All @@ -20,6 +20,7 @@ use crate::{
functions::coalesce,
get_conn,
naive_now,
now,
DbPool,
DELETED_REPLACEMENT_TEXT,
FETCH_LIMIT_MAX,
Expand All @@ -30,7 +31,7 @@ use crate::{
use ::url::Url;
use chrono::{DateTime, Utc};
use diesel::{
dsl::insert_into,
dsl::{count, insert_into, not},
result::Error,
DecoratableTarget,
ExpressionMethods,
Expand Down Expand Up @@ -169,6 +170,7 @@ impl Post {
let object_id: DbUrl = object_id.into();
post::table
.filter(post::ap_id.eq(object_id))
.filter(post::scheduled_publish_time.is_null())
.first(conn)
.await
.optional()
Expand Down Expand Up @@ -242,6 +244,28 @@ impl Post {
.get_results::<Self>(conn)
.await
}

pub async fn user_scheduled_post_count(
person_id: PersonId,
pool: &mut DbPool<'_>,
) -> Result<i64, Error> {
let conn = &mut get_conn(pool).await?;

post::table
.inner_join(person::table)
.inner_join(community::table)
// find all posts which have scheduled_publish_time that is in the past
.filter(post::scheduled_publish_time.is_not_null())
.filter(coalesce(post::scheduled_publish_time, now()).lt(now()))
// make sure the post and community are still around
.filter(not(post::deleted.or(post::removed)))
.filter(not(community::removed.or(community::deleted)))
// only posts by specified user
.filter(post::creator_id.eq(person_id))
.select(count(post::id))
.first::<i64>(conn)
.await
}
}

#[async_trait]
Expand Down Expand Up @@ -456,6 +480,7 @@ mod tests {
featured_community: false,
featured_local: false,
url_content_type: None,
scheduled_publish_time: None,
};

// Post Like
Expand Down
1 change: 1 addition & 0 deletions crates/db_schema/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@ diesel::table! {
featured_local -> Bool,
url_content_type -> Nullable<Text>,
alt_text -> Nullable<Text>,
scheduled_publish_time -> Nullable<Timestamptz>
}
}

Expand Down
4 changes: 4 additions & 0 deletions crates/db_schema/src/source/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub struct Post {
pub url_content_type: Option<String>,
/// An optional alt_text, usable for image posts.
pub alt_text: Option<String>,
/// Time at which the post will be published. None means publish immediately.
pub scheduled_publish_time: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, TypedBuilder)]
Expand Down Expand Up @@ -90,6 +92,7 @@ pub struct PostInsertForm {
pub featured_local: Option<bool>,
pub url_content_type: Option<String>,
pub alt_text: Option<String>,
pub scheduled_publish_time: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Default)]
Expand All @@ -116,6 +119,7 @@ pub struct PostUpdateForm {
pub featured_local: Option<bool>,
pub url_content_type: Option<Option<String>>,
pub alt_text: Option<Option<String>>,
pub scheduled_publish_time: Option<Option<DateTime<Utc>>>,
}

#[derive(PartialEq, Eq, Debug)]
Expand Down
1 change: 1 addition & 0 deletions crates/db_views/src/comment_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1083,6 +1083,7 @@ mod tests {
featured_community: false,
featured_local: false,
url_content_type: None,
scheduled_publish_time: None,
},
community: Community {
id: data.inserted_community.id,
Expand Down
12 changes: 10 additions & 2 deletions crates/db_views/src/post_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,18 @@ fn queries<'a>() -> Queries<
// hide posts from deleted communities
query = query.filter(community::deleted.eq(false));

// only show deleted posts to creator
// only creator can see deleted posts and unpublished scheduled posts
if let Some(person_id) = options.local_user.person_id() {
query = query.filter(post::deleted.eq(false).or(post::creator_id.eq(person_id)));
query = query.filter(
post::scheduled_publish_time
.is_null()
.or(post::creator_id.eq(person_id)),
);
} else {
query = query.filter(post::deleted.eq(false));
query = query
.filter(post::deleted.eq(false))
.filter(post::scheduled_publish_time.is_null());
}

// only show removed posts to admin when viewing user profile
Expand Down Expand Up @@ -1686,6 +1693,7 @@ mod tests {
featured_community: false,
featured_local: false,
url_content_type: None,
scheduled_publish_time: None,
},
my_vote: None,
unread_comments: 0,
Expand Down
2 changes: 2 additions & 0 deletions crates/utils/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ pub enum LemmyErrorType {
Unknown(String),
CantDeleteSite,
UrlLengthOverflow,
PostScheduleTimeMustBeInFuture,
TooManyScheduledPosts,
}

cfg_if! {
Expand Down
3 changes: 3 additions & 0 deletions migrations/2024-09-16-095656_schedule-post/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ALTER TABLE post
DROP COLUMN scheduled_publish_time;

5 changes: 5 additions & 0 deletions migrations/2024-09-16-095656_schedule-post/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ALTER TABLE post
ADD COLUMN scheduled_publish_time timestamptz;
dessalines marked this conversation as resolved.
Show resolved Hide resolved

CREATE INDEX idx_post_scheduled_publish_time ON post (scheduled_publish_time);

Loading