From: Dessalines Date: Sat, 8 Feb 2020 04:05:15 +0000 (-0500) Subject: Add new comments views to main and community pages. Fixes #480 X-Git-Url: http://these/git/%7B?a=commitdiff_plain;h=ecd10482a6815fc3b51b2da7cd5f494c01c385e6;p=lemmy.git Add new comments views to main and community pages. Fixes #480 --- diff --git a/README.md b/README.md index fcb07e72..47290953 100644 --- a/README.md +++ b/README.md @@ -130,19 +130,19 @@ If you'd like to add translations, take a look at the [English translation file] lang | done | missing ---- | ---- | ------- -ca | 97% | cross_posted_to,old,support_on_liberapay,post_title_too_long,time,action -de | 86% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,old,docs,message_sent,messages,old_password,matrix_user_id,private_message_disclaimer,send_notifications_to_email,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -fa | 71% | cross_post,cross_posted_to,subscribed_to_communities,trending_communities,create_private_message,send_secure_message,send_message,message,mod,mods,moderates,remove_as_mod,appoint_as_mod,modlog,stickied,ban,ban_from_site,unban,unban_from_site,banned,number_of_subscribers,subscribers,both,saved,unsubscribe,subscribe,subscribed,old,api,docs,inbox,inbox_for,message_sent,notifications_error,messages,no_email_setup,matrix_user_id,private_message_disclaimer,url,body,copy_suggested_title,community,expand_here,subscribe_to_communities,theme,sponsor_message,support_on_liberapay,general_sponsors,joined,by,to,from,landing_0,logged_in,community_moderator_already_exists,community_follower_already_exists,community_user_already_banned,post_title_too_long,no_slurs,admin_already_created,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -eo | 74% | cross_posted_to,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,theme,support_on_liberapay,donate_to_lemmy,donate,from,are_you_sure,yes,no,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -es | 99% | cross_posted_to,post_title_too_long -fi | 97% | cross_posted_to,old,support_on_liberapay,post_title_too_long,time,action -fr | 82% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -it | 82% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -nl | 98% | cross_posted_to,post_title_too_long,time,action -pt-br | 100% | post_title_too_long -ru | 70% | cross_posts,cross_post,cross_posted_to,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,recent_comments,theme,support_on_liberapay,donate_to_lemmy,donate,monero,by,to,from,transfer_community,transfer_site,are_you_sure,yes,no,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -sv | 81% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,support_on_liberapay,donate_to_lemmy,donate,from,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action -zh | 69% | cross_posts,cross_post,cross_posted_to,users,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,settings,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,recent_comments,nsfw,show_nsfw,theme,donate_to_lemmy,donate,monero,by,to,from,transfer_community,transfer_site,are_you_sure,yes,no,logged_in,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +ca | 97% | cross_posted_to,old,support_on_liberapay,couldnt_get_comments,post_title_too_long,time,action +de | 86% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,old,docs,message_sent,messages,old_password,matrix_user_id,private_message_disclaimer,send_notifications_to_email,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +fa | 71% | cross_post,cross_posted_to,subscribed_to_communities,trending_communities,create_private_message,send_secure_message,send_message,message,mod,mods,moderates,remove_as_mod,appoint_as_mod,modlog,stickied,ban,ban_from_site,unban,unban_from_site,banned,number_of_subscribers,subscribers,both,saved,unsubscribe,subscribe,subscribed,old,api,docs,inbox,inbox_for,message_sent,notifications_error,messages,no_email_setup,matrix_user_id,private_message_disclaimer,url,body,copy_suggested_title,community,expand_here,subscribe_to_communities,theme,sponsor_message,support_on_liberapay,general_sponsors,joined,by,to,from,landing_0,logged_in,couldnt_get_comments,community_moderator_already_exists,community_follower_already_exists,community_user_already_banned,post_title_too_long,no_slurs,admin_already_created,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +eo | 73% | cross_posted_to,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,theme,support_on_liberapay,donate_to_lemmy,donate,from,are_you_sure,yes,no,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +es | 99% | cross_posted_to,couldnt_get_comments,post_title_too_long +fi | 97% | cross_posted_to,old,support_on_liberapay,couldnt_get_comments,post_title_too_long,time,action +fr | 81% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +it | 82% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,donate_to_lemmy,donate,from,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +nl | 98% | cross_posted_to,couldnt_get_comments,post_title_too_long,time,action +pt-br | 99% | couldnt_get_comments,post_title_too_long +ru | 70% | cross_posts,cross_post,cross_posted_to,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,recent_comments,theme,support_on_liberapay,donate_to_lemmy,donate,monero,by,to,from,transfer_community,transfer_site,are_you_sure,yes,no,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +sv | 81% | cross_posted_to,create_private_message,send_secure_message,send_message,message,avatar,upload_avatar,show_avatars,archive_link,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,support_on_liberapay,donate_to_lemmy,donate,from,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action +zh | 69% | cross_posts,cross_post,cross_posted_to,users,number_of_communities,create_private_message,send_secure_message,send_message,message,preview,upload_image,avatar,upload_avatar,show_avatars,formatting_help,view_source,sticky,unsticky,archive_link,settings,stickied,delete_account,delete_account_confirm,banned,creator,number_online,old,docs,replies,mentions,message_sent,messages,old_password,forgot_password,reset_password_mail_sent,password_change,new_password,no_email_setup,matrix_user_id,private_message_disclaimer,send_notifications_to_email,language,browser_default,downvotes_disabled,enable_downvotes,open_registration,registration_closed,enable_nsfw,recent_comments,nsfw,show_nsfw,theme,donate_to_lemmy,donate,monero,by,to,from,transfer_community,transfer_site,are_you_sure,yes,no,logged_in,couldnt_get_comments,post_title_too_long,email_already_exists,couldnt_create_private_message,no_private_message_edit_allowed,couldnt_update_private_message,time,action If you'd like to update this report, run: diff --git a/server/migrations/2020-02-07-210055_add_comment_subscribed/down.sql b/server/migrations/2020-02-07-210055_add_comment_subscribed/down.sql new file mode 100644 index 00000000..b6120d15 --- /dev/null +++ b/server/migrations/2020-02-07-210055_add_comment_subscribed/down.sql @@ -0,0 +1,206 @@ + +drop view reply_view; +drop view user_mention_view; +drop view user_mention_mview; +drop view comment_view; +drop view comment_mview; +drop materialized view comment_aggregates_mview; +drop view comment_aggregates_view; + +-- reply and comment view +create view comment_aggregates_view as +select +c.*, +(select community_id from post p where p.id = c.post_id), +(select u.banned from user_ u where c.creator_id = u.id) as banned, +(select cb.id::bool from community_user_ban cb, post p where c.creator_id = cb.user_id and p.id = c.post_id and p.community_id = cb.community_id) as banned_from_community, +(select name from user_ where c.creator_id = user_.id) as creator_name, +(select avatar from user_ where c.creator_id = user_.id) as creator_avatar, +coalesce(sum(cl.score), 0) as score, +count (case when cl.score = 1 then 1 else null end) as upvotes, +count (case when cl.score = -1 then 1 else null end) as downvotes +from comment c +left join comment_like cl on c.id = cl.comment_id +group by c.id; + +create materialized view comment_aggregates_mview as select * from comment_aggregates_view; + +create unique index idx_comment_aggregates_mview_id on comment_aggregates_mview (id); + +create view comment_view as +with all_comment as +( + select + ca.* + from comment_aggregates_view ca +) + +select +ac.*, +u.id as user_id, +coalesce(cl.score, 0) as my_vote, +(select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id + +union all + +select + ac.*, + null as user_id, + null as my_vote, + null as saved +from all_comment ac +; + +create view comment_mview as +with all_comment as +( + select + ca.* + from comment_aggregates_mview ca +) + +select +ac.*, +u.id as user_id, +coalesce(cl.score, 0) as my_vote, +(select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id + +union all + +select + ac.*, + null as user_id, + null as my_vote, + null as saved +from all_comment ac +; + + +-- Do the reply_view referencing the comment_mview +create view reply_view as +with closereply as ( + select + c2.id, + c2.creator_id as sender_id, + c.creator_id as recipient_id + from comment c + inner join comment c2 on c.id = c2.parent_id + where c2.creator_id != c.creator_id + -- Do union where post is null + union + select + c.id, + c.creator_id as sender_id, + p.creator_id as recipient_id + from comment c, post p + where c.post_id = p.id and c.parent_id is null and c.creator_id != p.creator_id +) +select cv.*, +closereply.recipient_id +from comment_mview cv, closereply +where closereply.id = cv.id +; + +-- user mention +create view user_mention_view as +select + c.id, + um.id as user_mention_id, + c.creator_id, + c.post_id, + c.parent_id, + c.content, + c.removed, + um.read, + c.published, + c.updated, + c.deleted, + c.community_id, + c.banned, + c.banned_from_community, + c.creator_name, + c.creator_avatar, + c.score, + c.upvotes, + c.downvotes, + c.user_id, + c.my_vote, + c.saved, + um.recipient_id +from user_mention um, comment_view c +where um.comment_id = c.id; + + +create view user_mention_mview as +with all_comment as +( + select + ca.* + from comment_aggregates_mview ca +) + +select + ac.id, + um.id as user_mention_id, + ac.creator_id, + ac.post_id, + ac.parent_id, + ac.content, + ac.removed, + um.read, + ac.published, + ac.updated, + ac.deleted, + ac.community_id, + ac.banned, + ac.banned_from_community, + ac.creator_name, + ac.creator_avatar, + ac.score, + ac.upvotes, + ac.downvotes, + u.id as user_id, + coalesce(cl.score, 0) as my_vote, + (select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved, + um.recipient_id +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id +left join user_mention um on um.comment_id = ac.id + +union all + +select + ac.id, + um.id as user_mention_id, + ac.creator_id, + ac.post_id, + ac.parent_id, + ac.content, + ac.removed, + um.read, + ac.published, + ac.updated, + ac.deleted, + ac.community_id, + ac.banned, + ac.banned_from_community, + ac.creator_name, + ac.creator_avatar, + ac.score, + ac.upvotes, + ac.downvotes, + null as user_id, + null as my_vote, + null as saved, + um.recipient_id +from all_comment ac +left join user_mention um on um.comment_id = ac.id +; + diff --git a/server/migrations/2020-02-07-210055_add_comment_subscribed/up.sql b/server/migrations/2020-02-07-210055_add_comment_subscribed/up.sql new file mode 100644 index 00000000..8836a571 --- /dev/null +++ b/server/migrations/2020-02-07-210055_add_comment_subscribed/up.sql @@ -0,0 +1,220 @@ + +-- Adding community name, hot_rank, to comment_view, user_mention_view, and subscribed to comment_view + +-- Rebuild the comment view +drop view reply_view; +drop view user_mention_view; +drop view user_mention_mview; +drop view comment_view; +drop view comment_mview; +drop materialized view comment_aggregates_mview; +drop view comment_aggregates_view; + +-- reply and comment view +create view comment_aggregates_view as +select +c.*, +(select community_id from post p where p.id = c.post_id), +(select co.name from post p, community co where p.id = c.post_id and p.community_id = co.id) as community_name, +(select u.banned from user_ u where c.creator_id = u.id) as banned, +(select cb.id::bool from community_user_ban cb, post p where c.creator_id = cb.user_id and p.id = c.post_id and p.community_id = cb.community_id) as banned_from_community, +(select name from user_ where c.creator_id = user_.id) as creator_name, +(select avatar from user_ where c.creator_id = user_.id) as creator_avatar, +coalesce(sum(cl.score), 0) as score, +count (case when cl.score = 1 then 1 else null end) as upvotes, +count (case when cl.score = -1 then 1 else null end) as downvotes, +hot_rank(coalesce(sum(cl.score) , 0), c.published) as hot_rank +from comment c +left join comment_like cl on c.id = cl.comment_id +group by c.id; + +create materialized view comment_aggregates_mview as select * from comment_aggregates_view; + +create unique index idx_comment_aggregates_mview_id on comment_aggregates_mview (id); + +create view comment_view as +with all_comment as +( + select + ca.* + from comment_aggregates_view ca +) + +select +ac.*, +u.id as user_id, +coalesce(cl.score, 0) as my_vote, +(select cf.id::boolean from community_follower cf where u.id = cf.user_id and ac.community_id = cf.community_id) as subscribed, +(select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id + +union all + +select + ac.*, + null as user_id, + null as my_vote, + null as subscribed, + null as saved +from all_comment ac +; + +create view comment_mview as +with all_comment as +( + select + ca.* + from comment_aggregates_mview ca +) + +select +ac.*, +u.id as user_id, +coalesce(cl.score, 0) as my_vote, +(select cf.id::boolean from community_follower cf where u.id = cf.user_id and ac.community_id = cf.community_id) as subscribed, +(select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id + +union all + +select + ac.*, + null as user_id, + null as my_vote, + null as subscribed, + null as saved +from all_comment ac +; + +-- Do the reply_view referencing the comment_mview +create view reply_view as +with closereply as ( + select + c2.id, + c2.creator_id as sender_id, + c.creator_id as recipient_id + from comment c + inner join comment c2 on c.id = c2.parent_id + where c2.creator_id != c.creator_id + -- Do union where post is null + union + select + c.id, + c.creator_id as sender_id, + p.creator_id as recipient_id + from comment c, post p + where c.post_id = p.id and c.parent_id is null and c.creator_id != p.creator_id +) +select cv.*, +closereply.recipient_id +from comment_mview cv, closereply +where closereply.id = cv.id +; + +-- user mention +create view user_mention_view as +select + c.id, + um.id as user_mention_id, + c.creator_id, + c.post_id, + c.parent_id, + c.content, + c.removed, + um.read, + c.published, + c.updated, + c.deleted, + c.community_id, + c.community_name, + c.banned, + c.banned_from_community, + c.creator_name, + c.creator_avatar, + c.score, + c.upvotes, + c.downvotes, + c.hot_rank, + c.user_id, + c.my_vote, + c.saved, + um.recipient_id +from user_mention um, comment_view c +where um.comment_id = c.id; + + +create view user_mention_mview as +with all_comment as +( + select + ca.* + from comment_aggregates_mview ca +) + +select + ac.id, + um.id as user_mention_id, + ac.creator_id, + ac.post_id, + ac.parent_id, + ac.content, + ac.removed, + um.read, + ac.published, + ac.updated, + ac.deleted, + ac.community_id, + ac.community_name, + ac.banned, + ac.banned_from_community, + ac.creator_name, + ac.creator_avatar, + ac.score, + ac.upvotes, + ac.downvotes, + ac.hot_rank, + u.id as user_id, + coalesce(cl.score, 0) as my_vote, + (select cs.id::bool from comment_saved cs where u.id = cs.user_id and cs.comment_id = ac.id) as saved, + um.recipient_id +from user_ u +cross join all_comment ac +left join comment_like cl on u.id = cl.user_id and ac.id = cl.comment_id +left join user_mention um on um.comment_id = ac.id + +union all + +select + ac.id, + um.id as user_mention_id, + ac.creator_id, + ac.post_id, + ac.parent_id, + ac.content, + ac.removed, + um.read, + ac.published, + ac.updated, + ac.deleted, + ac.community_id, + ac.community_name, + ac.banned, + ac.banned_from_community, + ac.creator_name, + ac.creator_avatar, + ac.score, + ac.upvotes, + ac.downvotes, + ac.hot_rank, + null as user_id, + null as my_vote, + null as saved, + um.recipient_id +from all_comment ac +left join user_mention um on um.comment_id = ac.id +; + diff --git a/server/src/api/comment.rs b/server/src/api/comment.rs index 775085e9..5c614966 100644 --- a/server/src/api/comment.rs +++ b/server/src/api/comment.rs @@ -2,6 +2,7 @@ use super::*; use crate::send_email; use crate::settings::Settings; use diesel::PgConnection; +use std::str::FromStr; #[derive(Serialize, Deserialize)] pub struct CreateComment { @@ -47,6 +48,21 @@ pub struct CreateCommentLike { auth: String, } +#[derive(Serialize, Deserialize)] +pub struct GetComments { + type_: String, + sort: String, + page: Option, + limit: Option, + pub community_id: Option, + auth: Option, +} + +#[derive(Serialize, Deserialize)] +pub struct GetCommentsResponse { + comments: Vec, +} + impl Perform for Oper { fn perform(&self, conn: &PgConnection) -> Result { let data: &CreateComment = &self.data; @@ -456,3 +472,40 @@ impl Perform for Oper { }) } } + +impl Perform for Oper { + fn perform(&self, conn: &PgConnection) -> Result { + let data: &GetComments = &self.data; + + let user_claims: Option = match &data.auth { + Some(auth) => match Claims::decode(&auth) { + Ok(claims) => Some(claims.claims), + Err(_e) => None, + }, + None => None, + }; + + let user_id = match &user_claims { + Some(claims) => Some(claims.id), + None => None, + }; + + let type_ = ListingType::from_str(&data.type_)?; + let sort = SortType::from_str(&data.sort)?; + + let comments = match CommentQueryBuilder::create(&conn) + .listing_type(type_) + .sort(&sort) + .for_community_id(data.community_id) + .my_user_id(user_id) + .page(data.page) + .limit(data.limit) + .list() + { + Ok(comments) => comments, + Err(_e) => return Err(APIError::err("couldnt_get_comments").into()), + }; + + Ok(GetCommentsResponse { comments }) + } +} diff --git a/server/src/db/comment_view.rs b/server/src/db/comment_view.rs index febf18b7..01e1bbaf 100644 --- a/server/src/db/comment_view.rs +++ b/server/src/db/comment_view.rs @@ -15,6 +15,7 @@ table! { updated -> Nullable, deleted -> Bool, community_id -> Int4, + community_name -> Varchar, banned -> Bool, banned_from_community -> Bool, creator_name -> Varchar, @@ -22,8 +23,10 @@ table! { score -> BigInt, upvotes -> BigInt, downvotes -> BigInt, + hot_rank -> Int4, user_id -> Nullable, my_vote -> Nullable, + subscribed -> Nullable, saved -> Nullable, } } @@ -41,6 +44,7 @@ table! { updated -> Nullable, deleted -> Bool, community_id -> Int4, + community_name -> Varchar, banned -> Bool, banned_from_community -> Bool, creator_name -> Varchar, @@ -48,8 +52,10 @@ table! { score -> BigInt, upvotes -> BigInt, downvotes -> BigInt, + hot_rank -> Int4, user_id -> Nullable, my_vote -> Nullable, + subscribed -> Nullable, saved -> Nullable, } } @@ -70,6 +76,7 @@ pub struct CommentView { pub updated: Option, pub deleted: bool, pub community_id: i32, + pub community_name: String, pub banned: bool, pub banned_from_community: bool, pub creator_name: String, @@ -77,15 +84,19 @@ pub struct CommentView { pub score: i64, pub upvotes: i64, pub downvotes: i64, + pub hot_rank: i32, pub user_id: Option, pub my_vote: Option, + pub subscribed: Option, pub saved: Option, } pub struct CommentQueryBuilder<'a> { conn: &'a PgConnection, query: super::comment_view::comment_mview::BoxedQuery<'a, Pg>, + listing_type: ListingType, sort: &'a SortType, + for_community_id: Option, for_post_id: Option, for_creator_id: Option, search_term: Option, @@ -104,7 +115,9 @@ impl<'a> CommentQueryBuilder<'a> { CommentQueryBuilder { conn, query, + listing_type: ListingType::All, sort: &SortType::New, + for_community_id: None, for_post_id: None, for_creator_id: None, search_term: None, @@ -115,6 +128,11 @@ impl<'a> CommentQueryBuilder<'a> { } } + pub fn listing_type(mut self, listing_type: ListingType) -> Self { + self.listing_type = listing_type; + self + } + pub fn sort(mut self, sort: &'a SortType) -> Self { self.sort = sort; self @@ -130,6 +148,11 @@ impl<'a> CommentQueryBuilder<'a> { self } + pub fn for_community_id>(mut self, for_community_id: T) -> Self { + self.for_community_id = for_community_id.get_optional(); + self + } + pub fn search_term>(mut self, search_term: T) -> Self { self.search_term = search_term.get_optional(); self @@ -171,6 +194,10 @@ impl<'a> CommentQueryBuilder<'a> { query = query.filter(creator_id.eq(for_creator_id)); }; + if let Some(for_community_id) = self.for_community_id { + query = query.filter(community_id.eq(for_community_id)); + } + if let Some(for_post_id) = self.for_post_id { query = query.filter(post_id.eq(for_post_id)); }; @@ -179,12 +206,18 @@ impl<'a> CommentQueryBuilder<'a> { query = query.filter(content.ilike(fuzzy_search(&search_term))); }; + if let ListingType::Subscribed = self.listing_type { + query = query.filter(subscribed.eq(true)); + } + if self.saved_only { query = query.filter(saved.eq(true)); } query = match self.sort { - // SortType::Hot => query.order(hot_rank.desc(), published.desc()), + SortType::Hot => query + .order_by(hot_rank.desc()) + .then_order_by(published.desc()), SortType::New => query.order_by(published.desc()), SortType::TopAll => query.order_by(score.desc()), SortType::TopYear => query @@ -199,7 +232,7 @@ impl<'a> CommentQueryBuilder<'a> { SortType::TopDay => query .filter(published.gt(now - 1.days())) .order_by(score.desc()), - _ => query.order_by(published.desc()), + // _ => query.order_by(published.desc()), }; let (limit, offset) = limit_and_offset(self.page, self.limit); @@ -251,6 +284,7 @@ table! { updated -> Nullable, deleted -> Bool, community_id -> Int4, + community_name -> Varchar, banned -> Bool, banned_from_community -> Bool, creator_name -> Varchar, @@ -258,8 +292,10 @@ table! { score -> BigInt, upvotes -> BigInt, downvotes -> BigInt, + hot_rank -> Int4, user_id -> Nullable, my_vote -> Nullable, + subscribed -> Nullable, saved -> Nullable, recipient_id -> Int4, } @@ -281,6 +317,7 @@ pub struct ReplyView { pub updated: Option, pub deleted: bool, pub community_id: i32, + pub community_name: String, pub banned: bool, pub banned_from_community: bool, pub creator_name: String, @@ -288,8 +325,10 @@ pub struct ReplyView { pub score: i64, pub upvotes: i64, pub downvotes: i64, + pub hot_rank: i32, pub user_id: Option, pub my_vote: Option, + pub subscribed: Option, pub saved: Option, pub recipient_id: i32, } @@ -474,6 +513,7 @@ mod tests { creator_id: inserted_user.id, post_id: inserted_post.id, community_id: inserted_community.id, + community_name: inserted_community.name.to_owned(), parent_id: None, removed: false, deleted: false, @@ -486,9 +526,11 @@ mod tests { creator_avatar: None, score: 1, downvotes: 0, + hot_rank: 0, upvotes: 1, user_id: None, my_vote: None, + subscribed: None, saved: None, }; @@ -498,6 +540,7 @@ mod tests { creator_id: inserted_user.id, post_id: inserted_post.id, community_id: inserted_community.id, + community_name: inserted_community.name.to_owned(), parent_id: None, removed: false, deleted: false, @@ -510,21 +553,26 @@ mod tests { creator_avatar: None, score: 1, downvotes: 0, + hot_rank: 0, upvotes: 1, user_id: Some(inserted_user.id), my_vote: Some(1), + subscribed: None, saved: None, }; - let read_comment_views_no_user = CommentQueryBuilder::create(&conn) + let mut read_comment_views_no_user = CommentQueryBuilder::create(&conn) .for_post_id(inserted_post.id) .list() .unwrap(); - let read_comment_views_with_user = CommentQueryBuilder::create(&conn) + read_comment_views_no_user[0].hot_rank = 0; + + let mut read_comment_views_with_user = CommentQueryBuilder::create(&conn) .for_post_id(inserted_post.id) .my_user_id(inserted_user.id) .list() .unwrap(); + read_comment_views_with_user[0].hot_rank = 0; let like_removed = CommentLike::remove(&conn, &comment_like_form).unwrap(); let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap(); diff --git a/server/src/db/post_view.rs b/server/src/db/post_view.rs index 4d09308d..d6a1d191 100644 --- a/server/src/db/post_view.rs +++ b/server/src/db/post_view.rs @@ -121,6 +121,9 @@ pub struct PostQueryBuilder<'a> { sort: &'a SortType, my_user_id: Option, for_creator_id: Option, + for_community_id: Option, + search_term: Option, + url_search: Option, show_nsfw: bool, saved_only: bool, unread_only: bool, @@ -137,10 +140,13 @@ impl<'a> PostQueryBuilder<'a> { PostQueryBuilder { conn, query, - my_user_id: None, - for_creator_id: None, listing_type: ListingType::All, sort: &SortType::Hot, + my_user_id: None, + for_creator_id: None, + for_community_id: None, + search_term: None, + url_search: None, show_nsfw: true, saved_only: false, unread_only: false, @@ -160,38 +166,22 @@ impl<'a> PostQueryBuilder<'a> { } pub fn for_community_id>(mut self, for_community_id: T) -> Self { - use super::post_view::post_mview::dsl::*; - if let Some(for_community_id) = for_community_id.get_optional() { - self.query = self.query.filter(community_id.eq(for_community_id)); - self.query = self.query.then_order_by(stickied.desc()); - } + self.for_community_id = for_community_id.get_optional(); self } pub fn for_creator_id>(mut self, for_creator_id: T) -> Self { - if let Some(for_creator_id) = for_creator_id.get_optional() { - self.for_creator_id = Some(for_creator_id); - } + self.for_creator_id = for_creator_id.get_optional(); self } pub fn search_term>(mut self, search_term: T) -> Self { - use super::post_view::post_mview::dsl::*; - if let Some(search_term) = search_term.get_optional() { - let searcher = fuzzy_search(&search_term); - self.query = self - .query - .filter(name.ilike(searcher.to_owned())) - .or_filter(body.ilike(searcher)); - } + self.search_term = search_term.get_optional(); self } pub fn url_search>(mut self, url_search: T) -> Self { - use super::post_view::post_mview::dsl::*; - if let Some(url_search) = url_search.get_optional() { - self.query = self.query.filter(url.eq(url_search)); - } + self.url_search = url_search.get_optional(); self } @@ -234,6 +224,22 @@ impl<'a> PostQueryBuilder<'a> { query = query.filter(subscribed.eq(true)); } + if let Some(for_community_id) = self.for_community_id { + query = query.filter(community_id.eq(for_community_id)); + query = query.then_order_by(stickied.desc()); + } + + if let Some(url_search) = self.url_search { + query = query.filter(url.eq(url_search)); + } + + if let Some(search_term) = self.search_term { + let searcher = fuzzy_search(&search_term); + query = query + .filter(name.ilike(searcher.to_owned())) + .or_filter(body.ilike(searcher)); + } + query = match self.sort { SortType::Hot => query .then_order_by(hot_rank.desc()) diff --git a/server/src/db/user_mention_view.rs b/server/src/db/user_mention_view.rs index 1cf43984..8046747e 100644 --- a/server/src/db/user_mention_view.rs +++ b/server/src/db/user_mention_view.rs @@ -16,6 +16,7 @@ table! { updated -> Nullable, deleted -> Bool, community_id -> Int4, + community_name -> Varchar, banned -> Bool, banned_from_community -> Bool, creator_name -> Varchar, @@ -23,6 +24,7 @@ table! { score -> BigInt, upvotes -> BigInt, downvotes -> BigInt, + hot_rank -> Int4, user_id -> Nullable, my_vote -> Nullable, saved -> Nullable, @@ -44,6 +46,7 @@ table! { updated -> Nullable, deleted -> Bool, community_id -> Int4, + community_name -> Varchar, banned -> Bool, banned_from_community -> Bool, creator_name -> Varchar, @@ -51,6 +54,7 @@ table! { score -> BigInt, upvotes -> BigInt, downvotes -> BigInt, + hot_rank -> Int4, user_id -> Nullable, my_vote -> Nullable, saved -> Nullable, @@ -75,6 +79,7 @@ pub struct UserMentionView { pub updated: Option, pub deleted: bool, pub community_id: i32, + pub community_name: String, pub banned: bool, pub banned_from_community: bool, pub creator_name: String, @@ -82,6 +87,7 @@ pub struct UserMentionView { pub score: i64, pub upvotes: i64, pub downvotes: i64, + pub hot_rank: i32, pub user_id: Option, pub my_vote: Option, pub saved: Option, @@ -149,7 +155,9 @@ impl<'a> UserMentionQueryBuilder<'a> { .filter(recipient_id.eq(self.for_user_id)); query = match self.sort { - // SortType::Hot => query.order_by(hot_rank.desc()), + SortType::Hot => query + .order_by(hot_rank.desc()) + .then_order_by(published.desc()), SortType::New => query.order_by(published.desc()), SortType::TopAll => query.order_by(score.desc()), SortType::TopYear => query @@ -164,7 +172,7 @@ impl<'a> UserMentionQueryBuilder<'a> { SortType::TopDay => query .filter(published.gt(now - 1.days())) .order_by(score.desc()), - _ => query.order_by(published.desc()), + // _ => query.order_by(published.desc()), }; let (limit, offset) = limit_and_offset(self.page, self.limit); diff --git a/server/src/routes/index.rs b/server/src/routes/index.rs index b044833e..c1c363c9 100644 --- a/server/src/routes/index.rs +++ b/server/src/routes/index.rs @@ -6,7 +6,7 @@ pub fn config(cfg: &mut web::ServiceConfig) { cfg .route("/", web::get().to(index)) .route( - "/home/type/{type}/sort/{sort}/page/{page}", + "/home/data_type/{data_type}/listing_type/{listing_type}/sort/{sort}/page/{page}", web::get().to(index), ) .route("/login", web::get().to(index)) @@ -17,7 +17,10 @@ pub fn config(cfg: &mut web::ServiceConfig) { .route("/communities", web::get().to(index)) .route("/post/{id}/comment/{id2}", web::get().to(index)) .route("/post/{id}", web::get().to(index)) - .route("/c/{name}/sort/{sort}/page/{page}", web::get().to(index)) + .route( + "/c/{name}/data_type/{data_type}/sort/{sort}/page/{page}", + web::get().to(index), + ) .route("/c/{name}", web::get().to(index)) .route("/community/{id}", web::get().to(index)) .route( diff --git a/server/src/websocket/mod.rs b/server/src/websocket/mod.rs index c9a41a1f..a1feede2 100644 --- a/server/src/websocket/mod.rs +++ b/server/src/websocket/mod.rs @@ -45,4 +45,5 @@ pub enum UserOperation { EditPrivateMessage, GetPrivateMessages, UserJoin, + GetComments, } diff --git a/server/src/websocket/server.rs b/server/src/websocket/server.rs index bf3249e1..003b886e 100644 --- a/server/src/websocket/server.rs +++ b/server/src/websocket/server.rs @@ -121,6 +121,12 @@ impl ChatServer { sessions.remove(&id); } + // Also leave all post rooms + // This avoids double messages + for sessions in self.post_rooms.values_mut() { + sessions.remove(&id); + } + // If the room doesn't exist yet if self.community_rooms.get_mut(&community_id).is_none() { self.community_rooms.insert(community_id, HashSet::new()); @@ -139,6 +145,12 @@ impl ChatServer { sessions.remove(&id); } + // Also leave all communities + // This avoids double messages + for sessions in self.community_rooms.values_mut() { + sessions.remove(&id); + } + // If the room doesn't exist yet if self.post_rooms.get_mut(&post_id).is_none() { self.post_rooms.insert(post_id, HashSet::new()); @@ -243,6 +255,10 @@ impl ChatServer { self.send_user_room_message(recipient_id, &comment_reply_sent_str, id); } + // Send it to the community too + self.send_community_room_message(0, &comment_post_sent_str, id); + self.send_community_room_message(comment.comment.community_id, &comment_post_sent_str, id); + Ok(comment_user_sent_str) } @@ -613,6 +629,15 @@ fn parse_json_message(chat: &mut ChatServer, msg: StandardMessage) -> Result { + let get_comments: GetComments = serde_json::from_str(data)?; + if get_comments.community_id.is_none() { + // 0 is the "all" community + chat.join_community_room(0, msg.id); + } + let res = Oper::new(get_comments).perform(&conn)?; + to_json_string(&user_operation, &res) + } UserOperation::CreatePost => { chat.check_rate_limit_post(msg.id, true)?; let create_post: CreatePost = serde_json::from_str(data)?; diff --git a/ui/src/components/comment-node.tsx b/ui/src/components/comment-node.tsx index 3296a5c8..a67b1c35 100644 --- a/ui/src/components/comment-node.tsx +++ b/ui/src/components/comment-node.tsx @@ -58,7 +58,9 @@ interface CommentNodeProps { markable?: boolean; moderators: Array; admins: Array; + // TODO is this necessary, can't I get it from the node itself? postCreatorId?: number; + showCommunity?: boolean; } export class CommentNode extends Component { @@ -205,6 +207,14 @@ export class CommentNode extends Component { ) + {this.props.showCommunity && ( +
  • + {i18n.t('to')} + + {node.comment.community_name} + +
  • + )}
  • diff --git a/ui/src/components/comment-nodes.tsx b/ui/src/components/comment-nodes.tsx index 18faf1ac..fb700cc4 100644 --- a/ui/src/components/comment-nodes.tsx +++ b/ui/src/components/comment-nodes.tsx @@ -17,6 +17,7 @@ interface CommentNodesProps { viewOnly?: boolean; locked?: boolean; markable?: boolean; + showCommunity?: boolean; } export class CommentNodes extends Component< @@ -40,6 +41,7 @@ export class CommentNodes extends Component< admins={this.props.admins} postCreatorId={this.props.postCreatorId} markable={this.props.markable} + showCommunity={this.props.showCommunity} /> ))} diff --git a/ui/src/components/community.tsx b/ui/src/components/community.tsx index 069f9158..3e04a8bf 100644 --- a/ui/src/components/community.tsx +++ b/ui/src/components/community.tsx @@ -13,17 +13,31 @@ import { GetPostsForm, GetCommunityForm, ListingType, + DataType, GetPostsResponse, PostResponse, AddModToCommunityResponse, BanFromCommunityResponse, + Comment, + GetCommentsForm, + GetCommentsResponse, + CommentResponse, WebSocketJsonResponse, } from '../interfaces'; -import { WebSocketService, UserService } from '../services'; +import { WebSocketService } from '../services'; import { PostListings } from './post-listings'; +import { CommentNodes } from './comment-nodes'; import { SortSelect } from './sort-select'; +import { DataTypeSelect } from './data-type-select'; import { Sidebar } from './sidebar'; -import { wsJsonToRes, routeSortTypeToEnum, fetchLimit, toast } from '../utils'; +import { + wsJsonToRes, + fetchLimit, + toast, + getPageFromProps, + getSortTypeFromProps, + getDataTypeFromProps, +} from '../utils'; import { i18n } from '../i18next'; interface State { @@ -35,6 +49,8 @@ interface State { online: number; loading: boolean; posts: Array; + comments: Array; + dataType: DataType; sort: SortType; page: number; } @@ -65,27 +81,18 @@ export class Community extends Component { online: null, loading: true, posts: [], - sort: this.getSortTypeFromProps(this.props), - page: this.getPageFromProps(this.props), + comments: [], + dataType: getDataTypeFromProps(this.props), + sort: getSortTypeFromProps(this.props), + page: getPageFromProps(this.props), }; - getSortTypeFromProps(props: any): SortType { - return props.match.params.sort - ? routeSortTypeToEnum(props.match.params.sort) - : UserService.Instance.user - ? UserService.Instance.user.default_sort_type - : SortType.Hot; - } - - getPageFromProps(props: any): number { - return props.match.params.page ? Number(props.match.params.page) : 1; - } - constructor(props: any, context: any) { super(props, context); this.state = this.emptyState; this.handleSortChange = this.handleSortChange.bind(this); + this.handleDataTypeChange = this.handleDataTypeChange.bind(this); this.subscription = WebSocketService.Instance.subject .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) @@ -112,10 +119,11 @@ export class Community extends Component { nextProps.history.action == 'POP' || nextProps.history.action == 'PUSH' ) { - this.state.sort = this.getSortTypeFromProps(nextProps); - this.state.page = this.getPageFromProps(nextProps); + this.state.dataType = getDataTypeFromProps(nextProps); + this.state.sort = getSortTypeFromProps(nextProps); + this.state.page = getPageFromProps(nextProps); this.setState(this.state); - this.fetchPosts(); + this.fetchData(); } } @@ -145,7 +153,7 @@ export class Community extends Component { )} {this.selects()} - + {this.listings()} {this.paginator()}
    @@ -162,10 +170,31 @@ export class Community extends Component { ); } + listings() { + return this.state.dataType == DataType.Post ? ( + + ) : ( + this.state.comments.map(comment => ( +
    +
    + +
    +
    + )) + ); + } + selects() { return (
    - + + + + + { i.state.page++; i.setState(i.state); i.updateUrl(); - i.fetchPosts(); + i.fetchData(); window.scrollTo(0, 0); } @@ -215,7 +244,7 @@ export class Community extends Component { i.state.page--; i.setState(i.state); i.updateUrl(); - i.fetchPosts(); + i.fetchData(); window.scrollTo(0, 0); } @@ -225,26 +254,48 @@ export class Community extends Component { this.state.loading = true; this.setState(this.state); this.updateUrl(); - this.fetchPosts(); + this.fetchData(); + window.scrollTo(0, 0); + } + + handleDataTypeChange(val: DataType) { + this.state.dataType = val; + this.state.page = 1; + this.state.loading = true; + this.setState(this.state); + this.updateUrl(); + this.fetchData(); window.scrollTo(0, 0); } updateUrl() { + let dataTypeStr = DataType[this.state.dataType].toLowerCase(); let sortStr = SortType[this.state.sort].toLowerCase(); this.props.history.push( - `/c/${this.state.community.name}/sort/${sortStr}/page/${this.state.page}` + `/c/${this.state.community.name}/data_type/${dataTypeStr}/sort/${sortStr}/page/${this.state.page}` ); } - fetchPosts() { - let getPostsForm: GetPostsForm = { - page: this.state.page, - limit: fetchLimit, - sort: SortType[this.state.sort], - type_: ListingType[ListingType.Community], - community_id: this.state.community.id, - }; - WebSocketService.Instance.getPosts(getPostsForm); + fetchData() { + if (this.state.dataType == DataType.Post) { + let getPostsForm: GetPostsForm = { + page: this.state.page, + limit: fetchLimit, + sort: SortType[this.state.sort], + type_: ListingType[ListingType.Community], + community_id: this.state.community.id, + }; + WebSocketService.Instance.getPosts(getPostsForm); + } else { + let getCommentsForm: GetCommentsForm = { + page: this.state.page, + limit: fetchLimit, + sort: SortType[this.state.sort], + type_: ListingType[ListingType.Community], + community_id: this.state.community.id, + }; + WebSocketService.Instance.getComments(getCommentsForm); + } } parseMessage(msg: WebSocketJsonResponse) { @@ -255,7 +306,7 @@ export class Community extends Component { this.context.router.history.push('/'); return; } else if (msg.reconnect) { - this.fetchPosts(); + this.fetchData(); } else if (res.op == UserOperation.GetCommunity) { let data = res.data as GetCommunityResponse; this.state.community = data.community; @@ -264,7 +315,7 @@ export class Community extends Component { this.state.online = data.online; document.title = `/c/${this.state.community.name} - ${WebSocketService.Instance.site.name}`; this.setState(this.state); - this.fetchPosts(); + this.fetchData(); } else if (res.op == UserOperation.EditCommunity) { let data = res.data as CommunityResponse; this.state.community = data.community; @@ -319,6 +370,48 @@ export class Community extends Component { .forEach(p => (p.banned = data.banned)); this.setState(this.state); + } else if (res.op == UserOperation.GetComments) { + let data = res.data as GetCommentsResponse; + this.state.comments = data.comments; + this.state.loading = false; + this.setState(this.state); + } else if (res.op == UserOperation.EditComment) { + let data = res.data as CommentResponse; + + let found = this.state.comments.find(c => c.id == data.comment.id); + if (found) { + found.content = data.comment.content; + found.updated = data.comment.updated; + found.removed = data.comment.removed; + found.deleted = data.comment.deleted; + found.upvotes = data.comment.upvotes; + found.downvotes = data.comment.downvotes; + found.score = data.comment.score; + this.setState(this.state); + } + } else if (res.op == UserOperation.CreateComment) { + let data = res.data as CommentResponse; + + // Necessary since it might be a user reply + if (data.recipient_ids.length == 0) { + this.state.comments.unshift(data.comment); + this.setState(this.state); + } + } else if (res.op == UserOperation.SaveComment) { + let data = res.data as CommentResponse; + let found = this.state.comments.find(c => c.id == data.comment.id); + found.saved = data.comment.saved; + this.setState(this.state); + } else if (res.op == UserOperation.CreateCommentLike) { + let data = res.data as CommentResponse; + let found: Comment = this.state.comments.find( + c => c.id === data.comment.id + ); + found.score = data.comment.score; + found.upvotes = data.comment.upvotes; + found.downvotes = data.comment.downvotes; + if (data.comment.my_vote !== null) found.my_vote = data.comment.my_vote; + this.setState(this.state); } } } diff --git a/ui/src/components/data-type-select.tsx b/ui/src/components/data-type-select.tsx new file mode 100644 index 00000000..f2539c81 --- /dev/null +++ b/ui/src/components/data-type-select.tsx @@ -0,0 +1,65 @@ +import { Component, linkEvent } from 'inferno'; +import { DataType } from '../interfaces'; + +import { i18n } from '../i18next'; + +interface DataTypeSelectProps { + type_: DataType; + onChange?(val: DataType): any; +} + +interface DataTypeSelectState { + type_: DataType; +} + +export class DataTypeSelect extends Component< + DataTypeSelectProps, + DataTypeSelectState +> { + private emptyState: DataTypeSelectState = { + type_: this.props.type_, + }; + + constructor(props: any, context: any) { + super(props, context); + this.state = this.emptyState; + } + + render() { + return ( +
    + + +
    + ); + } + + handleTypeChange(i: DataTypeSelect, event: any) { + i.state.type_ = Number(event.target.value); + i.setState(i.state); + i.props.onChange(i.state.type_); + } +} diff --git a/ui/src/components/main.tsx b/ui/src/components/main.tsx index 161f5df4..92434360 100644 --- a/ui/src/components/main.tsx +++ b/ui/src/components/main.tsx @@ -12,30 +12,39 @@ import { SortType, GetSiteResponse, ListingType, + DataType, SiteResponse, GetPostsResponse, PostResponse, Post, GetPostsForm, + Comment, + GetCommentsForm, + GetCommentsResponse, + CommentResponse, AddAdminResponse, BanUserResponse, WebSocketJsonResponse, } from '../interfaces'; import { WebSocketService, UserService } from '../services'; import { PostListings } from './post-listings'; +import { CommentNodes } from './comment-nodes'; import { SortSelect } from './sort-select'; import { ListingTypeSelect } from './listing-type-select'; +import { DataTypeSelect } from './data-type-select'; import { SiteForm } from './site-form'; import { wsJsonToRes, repoUrl, mdToHtml, fetchLimit, - routeSortTypeToEnum, - routeListingTypeToEnum, pictshareAvatarThumbnail, showAvatars, toast, + getListingTypeFromProps, + getPageFromProps, + getSortTypeFromProps, + getDataTypeFromProps, } from '../utils'; import { i18n } from '../i18next'; import { T } from 'inferno-i18next'; @@ -47,7 +56,9 @@ interface MainState { showEditSite: boolean; loading: boolean; posts: Array; - type_: ListingType; + comments: Array; + listingType: ListingType; + dataType: DataType; sort: SortType; page: number; } @@ -79,38 +90,21 @@ export class Main extends Component { showEditSite: false, loading: true, posts: [], - type_: this.getListingTypeFromProps(this.props), - sort: this.getSortTypeFromProps(this.props), - page: this.getPageFromProps(this.props), + comments: [], + listingType: getListingTypeFromProps(this.props), + dataType: getDataTypeFromProps(this.props), + sort: getSortTypeFromProps(this.props), + page: getPageFromProps(this.props), }; - getListingTypeFromProps(props: any): ListingType { - return props.match.params.type - ? routeListingTypeToEnum(props.match.params.type) - : UserService.Instance.user - ? UserService.Instance.user.default_listing_type - : ListingType.All; - } - - getSortTypeFromProps(props: any): SortType { - return props.match.params.sort - ? routeSortTypeToEnum(props.match.params.sort) - : UserService.Instance.user - ? UserService.Instance.user.default_sort_type - : SortType.Hot; - } - - getPageFromProps(props: any): number { - return props.match.params.page ? Number(props.match.params.page) : 1; - } - constructor(props: any, context: any) { super(props, context); this.state = this.emptyState; this.handleEditCancel = this.handleEditCancel.bind(this); this.handleSortChange = this.handleSortChange.bind(this); - this.handleTypeChange = this.handleTypeChange.bind(this); + this.handleListingTypeChange = this.handleListingTypeChange.bind(this); + this.handleDataTypeChange = this.handleDataTypeChange.bind(this); this.subscription = WebSocketService.Instance.subject .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) @@ -133,7 +127,7 @@ export class Main extends Component { WebSocketService.Instance.listCommunities(listCommunitiesForm); - this.fetchPosts(); + this.fetchData(); } componentWillUnmount() { @@ -146,11 +140,12 @@ export class Main extends Component { nextProps.history.action == 'POP' || nextProps.history.action == 'PUSH' ) { - this.state.type_ = this.getListingTypeFromProps(nextProps); - this.state.sort = this.getSortTypeFromProps(nextProps); - this.state.page = this.getPageFromProps(nextProps); + this.state.listingType = getListingTypeFromProps(nextProps); + this.state.dataType = getDataTypeFromProps(nextProps); + this.state.sort = getSortTypeFromProps(nextProps); + this.state.page = getPageFromProps(nextProps); this.setState(this.state); - this.fetchPosts(); + this.fetchData(); } } @@ -251,10 +246,11 @@ export class Main extends Component { } updateUrl() { - let typeStr = ListingType[this.state.type_].toLowerCase(); + let listingTypeStr = ListingType[this.state.listingType].toLowerCase(); + let dataTypeStr = DataType[this.state.dataType].toLowerCase(); let sortStr = SortType[this.state.sort].toLowerCase(); this.props.history.push( - `/home/type/${typeStr}/sort/${sortStr}/page/${this.state.page}` + `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${this.state.page}` ); } @@ -392,11 +388,7 @@ export class Main extends Component { ) : (
    {this.selects()} - + {this.listings()} {this.paginator()}
    )} @@ -404,17 +396,41 @@ export class Main extends Component { ); } + listings() { + return this.state.dataType == DataType.Post ? ( + + ) : ( + this.state.comments.map(comment => ( +
    +
    + +
    +
    + )) + ); + } + selects() { return (
    - + + + - {this.state.type_ == ListingType.All && ( + {this.state.listingType == ListingType.All && ( { )} {UserService.Instance.user && - this.state.type_ == ListingType.Subscribed && ( + this.state.listingType == ListingType.Subscribed && ( { i.state.loading = true; i.setState(i.state); i.updateUrl(); - i.fetchPosts(); + i.fetchData(); window.scrollTo(0, 0); } @@ -497,7 +513,7 @@ export class Main extends Component { i.state.loading = true; i.setState(i.state); i.updateUrl(); - i.fetchPosts(); + i.fetchData(); window.scrollTo(0, 0); } @@ -507,28 +523,48 @@ export class Main extends Component { this.state.loading = true; this.setState(this.state); this.updateUrl(); - this.fetchPosts(); + this.fetchData(); window.scrollTo(0, 0); } - handleTypeChange(val: ListingType) { - this.state.type_ = val; + handleListingTypeChange(val: ListingType) { + this.state.listingType = val; this.state.page = 1; this.state.loading = true; this.setState(this.state); this.updateUrl(); - this.fetchPosts(); + this.fetchData(); window.scrollTo(0, 0); } - fetchPosts() { - let getPostsForm: GetPostsForm = { - page: this.state.page, - limit: fetchLimit, - sort: SortType[this.state.sort], - type_: ListingType[this.state.type_], - }; - WebSocketService.Instance.getPosts(getPostsForm); + handleDataTypeChange(val: DataType) { + this.state.dataType = val; + this.state.page = 1; + this.state.loading = true; + this.setState(this.state); + this.updateUrl(); + this.fetchData(); + window.scrollTo(0, 0); + } + + fetchData() { + if (this.state.dataType == DataType.Post) { + let getPostsForm: GetPostsForm = { + page: this.state.page, + limit: fetchLimit, + sort: SortType[this.state.sort], + type_: ListingType[this.state.listingType], + }; + WebSocketService.Instance.getPosts(getPostsForm); + } else { + let getCommentsForm: GetCommentsForm = { + page: this.state.page, + limit: fetchLimit, + sort: SortType[this.state.sort], + type_: ListingType[this.state.listingType], + }; + WebSocketService.Instance.getComments(getCommentsForm); + } } parseMessage(msg: WebSocketJsonResponse) { @@ -538,7 +574,7 @@ export class Main extends Component { toast(i18n.t(msg.error), 'danger'); return; } else if (msg.reconnect) { - this.fetchPosts(); + this.fetchData(); } else if (res.op == UserOperation.GetFollowedCommunities) { let data = res.data as GetFollowedCommunitiesResponse; this.state.subscribedCommunities = data.communities; @@ -574,7 +610,7 @@ export class Main extends Component { let data = res.data as PostResponse; // If you're on subscribed, only push it if you're subscribed. - if (this.state.type_ == ListingType.Subscribed) { + if (this.state.listingType == ListingType.Subscribed) { if ( this.state.subscribedCommunities .map(c => c.community_id) @@ -633,6 +669,59 @@ export class Main extends Component { .forEach(p => (p.banned = data.banned)); this.setState(this.state); + } else if (res.op == UserOperation.GetComments) { + let data = res.data as GetCommentsResponse; + this.state.comments = data.comments; + this.state.loading = false; + this.setState(this.state); + } else if (res.op == UserOperation.EditComment) { + let data = res.data as CommentResponse; + + let found = this.state.comments.find(c => c.id == data.comment.id); + if (found) { + found.content = data.comment.content; + found.updated = data.comment.updated; + found.removed = data.comment.removed; + found.deleted = data.comment.deleted; + found.upvotes = data.comment.upvotes; + found.downvotes = data.comment.downvotes; + found.score = data.comment.score; + this.setState(this.state); + } + } else if (res.op == UserOperation.CreateComment) { + let data = res.data as CommentResponse; + + // Necessary since it might be a user reply + if (data.recipient_ids.length == 0) { + // If you're on subscribed, only push it if you're subscribed. + if (this.state.listingType == ListingType.Subscribed) { + if ( + this.state.subscribedCommunities + .map(c => c.community_id) + .includes(data.comment.community_id) + ) { + this.state.comments.unshift(data.comment); + } + } else { + this.state.comments.unshift(data.comment); + } + this.setState(this.state); + } + } else if (res.op == UserOperation.SaveComment) { + let data = res.data as CommentResponse; + let found = this.state.comments.find(c => c.id == data.comment.id); + found.saved = data.comment.saved; + this.setState(this.state); + } else if (res.op == UserOperation.CreateCommentLike) { + let data = res.data as CommentResponse; + let found: Comment = this.state.comments.find( + c => c.id === data.comment.id + ); + found.score = data.comment.score; + found.upvotes = data.comment.upvotes; + found.downvotes = data.comment.downvotes; + if (data.comment.my_vote !== null) found.my_vote = data.comment.my_vote; + this.setState(this.state); } } } diff --git a/ui/src/components/user.tsx b/ui/src/components/user.tsx index da6aa8ce..effc9e1d 100644 --- a/ui/src/components/user.tsx +++ b/ui/src/components/user.tsx @@ -1034,20 +1034,24 @@ export class User extends Component { let data = res.data as CommentResponse; let found = this.state.comments.find(c => c.id == data.comment.id); - found.content = data.comment.content; - found.updated = data.comment.updated; - found.removed = data.comment.removed; - found.deleted = data.comment.deleted; - found.upvotes = data.comment.upvotes; - found.downvotes = data.comment.downvotes; - found.score = data.comment.score; - - this.setState(this.state); + if (found) { + found.content = data.comment.content; + found.updated = data.comment.updated; + found.removed = data.comment.removed; + found.deleted = data.comment.deleted; + found.upvotes = data.comment.upvotes; + found.downvotes = data.comment.downvotes; + found.score = data.comment.score; + this.setState(this.state); + } } else if (res.op == UserOperation.CreateComment) { - // let res: CommentResponse = msg; - toast(i18n.t('reply_sent')); - // this.state.comments.unshift(res.comment); // TODO do this right - // this.setState(this.state); + let data = res.data as CommentResponse; + if ( + UserService.Instance.user && + data.comment.creator_id == UserService.Instance.user.id + ) { + toast(i18n.t('reply_sent')); + } } else if (res.op == UserOperation.SaveComment) { let data = res.data as CommentResponse; let found = this.state.comments.find(c => c.id == data.comment.id); diff --git a/ui/src/index.tsx b/ui/src/index.tsx index 8a9aa3c3..c56f6c4e 100644 --- a/ui/src/index.tsx +++ b/ui/src/index.tsx @@ -41,7 +41,7 @@ class Index extends Component { @@ -56,7 +56,7 @@ class Index extends Component { diff --git a/ui/src/interfaces.ts b/ui/src/interfaces.ts index 02c108aa..5736d375 100644 --- a/ui/src/interfaces.ts +++ b/ui/src/interfaces.ts @@ -42,6 +42,7 @@ export enum UserOperation { EditPrivateMessage, GetPrivateMessages, UserJoin, + GetComments, } export enum CommentSortType { @@ -57,6 +58,11 @@ export enum ListingType { Community, } +export enum DataType { + Post, + Comment, +} + export enum SortType { Hot, New, @@ -187,6 +193,7 @@ export interface Comment { published: string; updated?: string; community_id: number; + community_name: string; banned: boolean; banned_from_community: boolean; creator_name: string; @@ -194,8 +201,10 @@ export interface Comment { score: number; upvotes: number; downvotes: number; + hot_rank: number; user_id?: number; my_vote?: number; + subscribed?: number; saved?: boolean; user_mention_id?: number; // For mention type recipient_id?: number; @@ -659,6 +668,19 @@ export interface GetPostsResponse { posts: Array; } +export interface GetCommentsForm { + type_: string; + sort: string; + page?: number; + limit: number; + community_id?: number; + auth?: string; +} + +export interface GetCommentsResponse { + comments: Array; +} + export interface CreatePostLikeForm { post_id: number; score: number; diff --git a/ui/src/services/WebSocketService.ts b/ui/src/services/WebSocketService.ts index 6d951618..3df69457 100644 --- a/ui/src/services/WebSocketService.ts +++ b/ui/src/services/WebSocketService.ts @@ -38,6 +38,7 @@ import { PrivateMessageForm, EditPrivateMessageForm, GetPrivateMessagesForm, + GetCommentsForm, UserJoinForm, MessageType, WebSocketJsonResponse, @@ -172,6 +173,11 @@ export class WebSocketService { this.ws.send(this.wsSendWrapper(UserOperation.GetPosts, form)); } + public getComments(form: GetCommentsForm) { + this.setAuth(form, false); + this.ws.send(this.wsSendWrapper(UserOperation.GetComments, form)); + } + public likePost(form: CreatePostLikeForm) { this.setAuth(form); this.ws.send(this.wsSendWrapper(UserOperation.CreatePostLike, form)); diff --git a/ui/src/translations/en.ts b/ui/src/translations/en.ts index f71c203b..788bce79 100644 --- a/ui/src/translations/en.ts +++ b/ui/src/translations/en.ts @@ -201,6 +201,7 @@ export const en = { couldnt_like_comment: "Couldn't like comment.", couldnt_update_comment: "Couldn't update comment.", couldnt_save_comment: "Couldn't save comment.", + couldnt_get_comments: "Couldn't get comments.", no_comment_edit_allowed: 'Not allowed to edit comment.', no_post_edit_allowed: 'Not allowed to edit post.', no_community_edit_allowed: 'Not allowed to edit community.', diff --git a/ui/src/utils.ts b/ui/src/utils.ts index 9ad0920f..51836c6f 100644 --- a/ui/src/utils.ts +++ b/ui/src/utils.ts @@ -19,6 +19,7 @@ import { User, SortType, ListingType, + DataType, SearchType, WebSocketResponse, WebSocketJsonResponse, @@ -198,6 +199,10 @@ export function routeListingTypeToEnum(type: string): ListingType { return ListingType[capitalizeFirstLetter(type)]; } +export function routeDataTypeToEnum(type: string): DataType { + return DataType[capitalizeFirstLetter(type)]; +} + export function routeSearchTypeToEnum(type: string): SearchType { return SearchType[capitalizeFirstLetter(type)]; } @@ -519,3 +524,30 @@ function communitySearch(text: string, cb: any) { cb([]); } } + +export function getListingTypeFromProps(props: any): ListingType { + return props.match.params.listing_type + ? routeListingTypeToEnum(props.match.params.listing_type) + : UserService.Instance.user + ? UserService.Instance.user.default_listing_type + : ListingType.All; +} + +// TODO might need to add a user setting for this too +export function getDataTypeFromProps(props: any): DataType { + return props.match.params.data_type + ? routeDataTypeToEnum(props.match.params.data_type) + : DataType.Post; +} + +export function getSortTypeFromProps(props: any): SortType { + return props.match.params.sort + ? routeSortTypeToEnum(props.match.params.sort) + : UserService.Instance.user + ? UserService.Instance.user.default_sort_type + : SortType.Hot; +} + +export function getPageFromProps(props: any): number { + return props.match.params.page ? Number(props.match.params.page) : 1; +}