add: timelines, homepage

This commit is contained in:
trisua 2025-03-31 19:31:36 -04:00
parent 619184d02e
commit de53eec0e8
24 changed files with 440 additions and 40 deletions

View file

@ -49,6 +49,9 @@ pub const COMMUNITIES_FEED: &str = include_str!("./public/html/communities/feed.
pub const COMMUNITIES_POST: &str = include_str!("./public/html/communities/post.html"); pub const COMMUNITIES_POST: &str = include_str!("./public/html/communities/post.html");
pub const COMMUNITIES_SETTINGS: &str = include_str!("./public/html/communities/settings.html"); pub const COMMUNITIES_SETTINGS: &str = include_str!("./public/html/communities/settings.html");
pub const TIMELINES_HOME: &str = include_str!("./public/html/timelines/home.html");
pub const TIMELINES_POPULAR: &str = include_str!("./public/html/timelines/popular.html");
// langs // langs
pub const LANG_EN_US: &str = include_str!("./langs/en-US.toml"); pub const LANG_EN_US: &str = include_str!("./langs/en-US.toml");
@ -163,6 +166,9 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
write_template!(html_path->"communities/post.html"(crate::assets::COMMUNITIES_POST) --config=config); write_template!(html_path->"communities/post.html"(crate::assets::COMMUNITIES_POST) --config=config);
write_template!(html_path->"communities/settings.html"(crate::assets::COMMUNITIES_SETTINGS) --config=config); write_template!(html_path->"communities/settings.html"(crate::assets::COMMUNITIES_SETTINGS) --config=config);
write_template!(html_path->"timelines/home.html"(crate::assets::TIMELINES_HOME) -d "timelines" --config=config);
write_template!(html_path->"timelines/popular.html"(crate::assets::TIMELINES_POPULAR) --config=config);
html_path html_path
} }

View file

@ -3,6 +3,7 @@ version = "1.0.0"
[data] [data]
"general:link.home" = "Home" "general:link.home" = "Home"
"general:link.popular" = "Popular"
"general:link.communities" = "Communities" "general:link.communities" = "Communities"
"general:action.save" = "Save" "general:action.save" = "Save"
"general:action.delete" = "Delete" "general:action.delete" = "Delete"
@ -15,6 +16,7 @@ version = "1.0.0"
"dialog:action.no" = "No" "dialog:action.no" = "No"
"dialog:action.save_and_close" = "Save and close" "dialog:action.save_and_close" = "Save and close"
"auth:action.login" = "Login" "auth:action.login" = "Login"
"auth:action.register" = "Register" "auth:action.register" = "Register"
"auth:action.logout" = "Logout" "auth:action.logout" = "Logout"

View file

@ -136,6 +136,16 @@ article {
} }
/* typo */ /* typo */
pre {
font-family: monospace;
width: 100%;
max-width: 100%;
overflow: auto;
background: var(--color-lowered);
border-radius: var(--radius);
padding: 1rem;
}
svg.icon { svg.icon {
stroke: currentColor; stroke: currentColor;
width: 18px; width: 18px;
@ -242,7 +252,7 @@ img.contain {
object-fit: contain; object-fit: contain;
} }
/* avatar */ /* avatar/banner */
.avatar { .avatar {
--size: 50px; --size: 50px;
border-radius: calc(var(--radius) / 2); border-radius: calc(var(--radius) / 2);
@ -255,6 +265,11 @@ img.contain {
object-fit: cover; object-fit: cover;
} }
.banner {
border-radius: var(--radius);
max-height: 350px;
}
/* table */ /* table */
table { table {
border-collapse: collapse; border-collapse: collapse;
@ -375,12 +390,13 @@ button,
justify-content: center; justify-content: center;
align-items: center; align-items: center;
gap: 0.25rem; gap: 0.25rem;
font-size: 0.9rem;
text-decoration: none !important;
user-select: none;
/* personality */ /* personality */
background: var(--color-primary); background: var(--color-primary);
color: var(--color-text-primary); color: var(--color-text-primary);
font-weight: 600; font-weight: 600;
font-size: 0.9rem;
text-decoration: none !important;
} }
button.small, button.small,

View file

@ -2,7 +2,9 @@
<title>{{ community.context.display_name }} - {{ config.name }}</title> <title>{{ community.context.display_name }} - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav() }} {% endblock %} {% block body %} {{ macros::nav() }}
<article> <article>
<div class="content_container"> <div class="content_container flex flex-col gap-4">
{{ components::community_banner(id=community.id, community=community) }}
<div class="w-full flex gap-4 flex-collapse"> <div class="w-full flex gap-4 flex-collapse">
<div <div
class="lhs flex flex-col gap-2 sm:w-full" class="lhs flex flex-col gap-2 sm:w-full"
@ -10,9 +12,8 @@
> >
<div class="card-nest w-full"> <div class="card-nest w-full">
<div class="card flex gap-2" id="community_avatar_and_name"> <div class="card flex gap-2" id="community_avatar_and_name">
{{ {{ components::community_avatar(id=community.id,
components::community_avatar(id=community.id,size="72px") community=community, size="72px") }}
}}
<div class="flex flex-col"> <div class="flex flex-col">
<!-- prettier-ignore --> <!-- prettier-ignore -->
<h3 id="title" class="title"> <h3 id="title" class="title">

View file

@ -11,7 +11,7 @@
{% if community %} {% if community %}
<img <img
src="/api/v1/communities/{{ id }}/avatar" src="/api/v1/communities/{{ id }}/avatar"
alt="{{ community.title }}" alt="{{ community.title }}'s avatar"
class="avatar shadow" class="avatar shadow"
loading="lazy" loading="lazy"
style="--size: {{ size }}" style="--size: {{ size }}"
@ -19,11 +19,34 @@
{% else %} {% else %}
<img <img
src="/api/v1/communities/{{ id }}/avatar" src="/api/v1/communities/{{ id }}/avatar"
alt="{{ id }}" alt="{{ id }}'s avatar"
class="avatar shadow" class="avatar shadow"
loading="lazy" loading="lazy"
style="--size: {{ size }}" style="--size: {{ size }}"
/> />
{% endif %} {%- endmacro %} {% macro banner(username) -%}
<img
title="{{ username }}'s banner"
src="/api/v1/auth/profile/{{ username }}/banner"
alt="@{{ username }}'s banner"
class="banner shadow"
loading="lazy"
/>
{%- endmacro %} {% macro community_banner(id, community=false) -%} {% if
community %}
<img
src="/api/v1/communities/{{ id }}/banner"
alt="{{ community.title }}'s banner"
class="banner shadow"
loading="lazy"
/>
{% else %}
<img
src="/api/v1/communities/{{ id }}/banner"
alt="{{ id }}'s banner"
class="banner shadow"
loading="lazy"
/>
{% endif %} {%- endmacro %} {% macro community_listing_card(community) -%} {% endif %} {%- endmacro %} {% macro community_listing_card(community) -%}
<a <a
class="card w-full flex items-center gap-4" class="card w-full flex items-center gap-4"
@ -109,6 +132,8 @@ show_community=true) -%}
{{ components::likes(id=post.id, asset_type="Post", {{ components::likes(id=post.id, asset_type="Post",
likes=post.likes, dislikes=post.dislikes) }} likes=post.likes, dislikes=post.dislikes) }}
</div> </div>
{% else %}
<div></div>
{% endif %} {% endif %}
<div class="flex gap-1 buttons_box"> <div class="flex gap-1 buttons_box">

View file

@ -16,6 +16,14 @@ show_lhs=true) -%}
<span class="desktop">{{ text "general:link.home" }}</span> <span class="desktop">{{ text "general:link.home" }}</span>
</a> </a>
<a
href="/popular"
class="button {% if selected == 'popular' %}active{% endif %}"
>
{{ icon "trending-up" }}
<span class="desktop">{{ text "general:link.popular" }}</span>
</a>
{% if user %} {% if user %}
<a <a
href="/communities" href="/communities"
@ -72,6 +80,12 @@ show_lhs=true) -%}
{{ icon "log-out" }} {{ icon "log-out" }}
<span>{{ text "auth:action.logout" }}</span> <span>{{ text "auth:action.logout" }}</span>
</button> </button>
<div class="title"></div>
<a href="https://github.com/trisuaso/tetratto">
{{ icon "code" }}
<span>View source</span>
</a>
</div> </div>
</div> </div>
{% else %} {% else %}
@ -93,10 +107,28 @@ show_lhs=true) -%}
{{ icon "user-plus" }} {{ icon "user-plus" }}
<span>{{ text "auth:action.register" }}</span> <span>{{ text "auth:action.register" }}</span>
</a> </a>
<div class="title"></div>
<a href="https://github.com/trisuaso/tetratto">
{{ icon "code" }}
<span>View source</span>
</a>
</div> </div>
</div> </div>
{% endif %} {% endif %}
</div> </div>
</div> </div>
</nav> </nav>
{%- endmacro %} {% macro timelines_nav(selected="") -%}
<div class="pillmenu w-full">
<a href="/" class="{% if selected == 'home' %}active{% endif %}">
{{ icon "newspaper" }}
<span>{{ text "general:link.home" }}</span>
</a>
<a href="/popular" class="{% if selected == 'popular' %}active{% endif %}">
{{ icon "trending-up" }}
<span>{{ text "general:link.popular" }}</span>
</a>
</div>
{%- endmacro %} {%- endmacro %}

View file

@ -1,12 +1,26 @@
{% import "macros.html" as macros %} {% extends "root.html" %} {% block body %} {% import "macros.html" as macros %} {% extends "root.html" %} {% block head %}
{{ macros::nav(selected="home") }} <title>{{ config.name }}</title>
<main class="flex flex-col gap-2"> {% endblock %} {% block body %}
<div class="card-nest"> <main class="flex justify-center" style="padding-top: 2rem">
<div class="card"> <div class="flex flex-col gap-2" style="width: 20rem; max-width: 100%">
<b>✨ Welcome to <i>{{ config.name }}</i>!</b> <h1 class="w-full text-center">{{ config.name }}</h1>
<div class="card flex flex-col gap-2">
<a href="/auth/login" class="button w-full">
{{ icon "log-in" }}
<span>{{ text "auth:action.login" }}</span>
</a>
<a href="/auth/register" class="button w-full secondary">
{{ icon "heart" }}
<span>{{ text "auth:action.register" }}</span>
</a>
</div> </div>
<div class="card">We're still working on your feed...</div> <a href="/popular" class="button w-full quaternary">
{{ icon "trending-up" }}
<span>Explore popular feed</span>
</a>
</div> </div>
</main> </main>
{% endblock %} {% endblock %}

View file

@ -2,7 +2,9 @@
<title>{{ profile.username }} - {{ config.name }}</title> <title>{{ profile.username }} - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav() }} {% endblock %} {% block body %} {{ macros::nav() }}
<article> <article>
<div class="content_container"> <div class="content_container flex flex-col gap-4">
{{ components::banner(username=profile.username) }}
<div class="w-full flex gap-4 flex-collapse"> <div class="w-full flex gap-4 flex-collapse">
<div <div
class="lhs flex flex-col gap-2 sm:w-full" class="lhs flex flex-col gap-2 sm:w-full"

View file

@ -149,6 +149,11 @@
</form> </form>
</div> </div>
</div> </div>
<button onclick="save_settings()" id="save_button">
{{ icon "check" }}
<span>{{ text "general:action.save" }}</span>
</button>
</div> </div>
<div <div
@ -368,6 +373,18 @@
], ],
settings, settings,
); );
ui.generate_settings_ui(
profile_settings,
[
[
["private_profile", "Private profile"],
"{{ user.settings.private_profile }}",
"checkbox",
],
],
settings,
);
}); });
</script> </script>
</main> </main>

View file

@ -87,10 +87,10 @@
<pre><code id="link_filter_url"></code></pre> <pre><code id="link_filter_url"></code></pre>
<p>Are sure you want to go there?</p> <p>Are sure you want to go there?</p>
<hr /> <hr class="margin" />
<div class="flex gap-2"> <div class="flex gap-2">
<a <a
class="button primary bold" class="button primary"
id="link_filter_continue" id="link_filter_continue"
rel="noopener noreferrer" rel="noopener noreferrer"
target="_blank" target="_blank"
@ -99,7 +99,7 @@
{{ text "dialog:action.continue" }} {{ text "dialog:action.continue" }}
</a> </a>
<button <button
class="bold" class="secondary"
type="button" type="button"
onclick="document.getElementById('link_filter').close()" onclick="document.getElementById('link_filter').close()"
> >

View file

@ -0,0 +1,27 @@
{% import "macros.html" as macros %} {% extends "root.html" %} {% block head %}
<title>{{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav(selected="home") }}
<main class="flex flex-col gap-2">
<!-- prettier-ignore -->
{{ macros::timelines_nav(selected="home") }}
{% if list|length == 0 %}
<div class="card-nest">
<div class="card">
<b>✨ Welcome to <i>{{ config.name }}</i>!</b>
</div>
<div class="card">
Join some communities to populate your home timeline!
</div>
</div>
{% else %}
<!-- prettier-ignore -->
<div class="card w-full flex flex-col gap-2">
{% for post in list %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% endfor %}
</div>
{% endif %}
</main>
{% endblock %}

View file

@ -0,0 +1,14 @@
{% import "macros.html" as macros %} {% extends "root.html" %} {% block head %}
<title>Popular - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav(selected="popular") }}
<main class="flex flex-col gap-2">
{{ macros::timelines_nav(selected="popular") }}
<!-- prettier-ignore -->
<div class="card w-full flex flex-col gap-2">
{% for post in list %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% endfor %}
</div>
</main>
{% endblock %}

View file

@ -647,6 +647,24 @@ media_theme_pref();
}); });
self.define("render_settings_ui_field", (_, into_element, option) => { self.define("render_settings_ui_field", (_, into_element, option) => {
if (option.input_element_type === "checkbox") {
into_element.innerHTML += `<div class="card flex gap-2">
<input
type="checkbox"
onchange="window.set_setting_field('${option.key}', event.target.checked)"
placeholder="${option.key}"
name="${option.key}"
id="${option.key}"
${option.value === "true" ? "checked" : ""}
class="w-content"
/>
<label for="${option.key}"><b>${option.label.replaceAll("_", " ")}</b></label>
</div>`;
return;
}
into_element.innerHTML += `<div class="card-nest"> into_element.innerHTML += `<div class="card-nest">
<div class="card small"> <div class="card small">
<label for="${option.key}"><b>${option.label.replaceAll("_", " ")}</b></label> <label for="${option.key}"><b>${option.label.replaceAll("_", " ")}</b></label>

View file

@ -1,7 +1,8 @@
use super::render_error; use super::{PaginatedQuery, render_error};
use crate::{State, assets::initial_context, get_lang, get_user_from_token}; use crate::{State, assets::initial_context, get_lang, get_user_from_token};
use axum::{ use axum::{
Extension, Extension,
extract::Query,
response::{Html, IntoResponse}, response::{Html, IntoResponse},
}; };
use axum_extra::extract::CookieJar; use axum_extra::extract::CookieJar;
@ -22,14 +23,64 @@ pub async fn not_found(jar: CookieJar, Extension(data): Extension<State>) -> imp
} }
/// `/` /// `/`
pub async fn index_request(jar: CookieJar, Extension(data): Extension<State>) -> impl IntoResponse { pub async fn index_request(
jar: CookieJar,
Extension(data): Extension<State>,
Query(req): Query<PaginatedQuery>,
) -> impl IntoResponse {
let data = data.read().await;
let user = match get_user_from_token!(jar, data.0) {
Some(ua) => ua,
None => {
return {
let lang = get_lang!(jar, data.0);
let context = initial_context(&data.0.0, lang, &None).await;
Html(data.1.render("misc/index.html", &context).unwrap())
};
}
};
let list = match data
.0
.get_posts_from_user_communities(user.id, 12, req.page)
.await
{
Ok(l) => match data.0.fill_posts_with_community(l).await {
Ok(l) => l,
Err(e) => return Html(render_error(e, &jar, &data, &Some(user)).await),
},
Err(e) => return Html(render_error(e, &jar, &data, &Some(user)).await),
};
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &Some(user)).await;
context.insert("list", &list);
Html(data.1.render("timelines/home.html", &context).unwrap())
}
/// `/popular`
pub async fn popular_request(
jar: CookieJar,
Extension(data): Extension<State>,
Query(req): Query<PaginatedQuery>,
) -> impl IntoResponse {
let data = data.read().await; let data = data.read().await;
let user = get_user_from_token!(jar, data.0); let user = get_user_from_token!(jar, data.0);
let lang = get_lang!(jar, data.0); let list = match data.0.get_popular_posts(12, req.page).await {
let context = initial_context(&data.0.0, lang, &user).await; Ok(l) => match data.0.fill_posts_with_community(l).await {
Ok(l) => l,
Err(e) => return Html(render_error(e, &jar, &data, &user).await),
},
Err(e) => return Html(render_error(e, &jar, &data, &user).await),
};
Html(data.1.render("misc/index.html", &context).unwrap()) let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &user).await;
context.insert("list", &list);
Html(data.1.render("timelines/popular.html", &context).unwrap())
} }
/// `/notifs` /// `/notifs`

View file

@ -17,6 +17,7 @@ pub fn routes() -> Router {
Router::new() Router::new()
// misc // misc
.route("/", get(misc::index_request)) .route("/", get(misc::index_request))
.route("/popular", get(misc::popular_request))
.route("/notifs", get(misc::notifications_request)) .route("/notifs", get(misc::notifications_request))
.fallback_service(get(misc::not_found)) .fallback_service(get(misc::not_found))
// auth // auth

View file

@ -91,6 +91,26 @@ pub async fn posts_request(
} }
} }
// check for private profile
if other_user.settings.private_profile {
if let Some(ref ua) = user {
if data
.0
.get_userfollow_by_initiator_receiver(other_user.id, ua.id)
.await
.is_err()
{
return Err(Html(
render_error(Error::NotAllowed, &jar, &data, &user).await,
));
}
} else {
return Err(Html(
render_error(Error::NotAllowed, &jar, &data, &user).await,
));
}
}
// fetch data // fetch data
let posts = match data let posts = match data
.0 .0

View file

@ -139,7 +139,7 @@ impl DataManager {
Err(e) => return Err(Error::DatabaseConnection(e.to_string())), Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
}; };
let res = execute!(&conn, "DELETE FROM users WHERE id = $1", &[&(id as i64)]); let res = execute!(&conn, "DELETE FROM users WHERE id = $1", &[&(id as isize)]);
if let Err(e) = res { if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string())); return Err(Error::DatabaseError(e.to_string()));

View file

@ -36,7 +36,7 @@ macro_rules! auto_method {
Err(e) => return Err(Error::DatabaseConnection(e.to_string())), Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
}; };
let res = query_row!(&conn, $query, &[&(id as i64)], |x| { let res = query_row!(&conn, $query, &[&(id as isize)], |x| {
Ok(Self::$select_fn(x)) Ok(Self::$select_fn(x))
}); });
@ -59,7 +59,7 @@ macro_rules! auto_method {
Err(e) => return Err(Error::DatabaseConnection(e.to_string())), Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
}; };
let res = query_row!(&conn, $query, &[&(id as i64)], |x| { let res = query_row!(&conn, $query, &[&(id as isize)], |x| {
Ok(Self::$select_fn(x)) Ok(Self::$select_fn(x))
}); });

View file

@ -53,7 +53,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM memberships WHERE owner = $1 AND community = $2", "SELECT * FROM memberships WHERE owner = $1 AND community = $2",
&[&(owner as i64), &(community as i64)], &[&(owner as isize), &(community as isize)],
|x| { Ok(Self::get_membership_from_row(x)) } |x| { Ok(Self::get_membership_from_row(x)) }
); );
@ -74,7 +74,7 @@ impl DataManager {
let res = query_rows!( let res = query_rows!(
&conn, &conn,
"SELECT * FROM memberships WHERE owner = $1 AND role IS NOT 33", "SELECT * FROM memberships WHERE owner = $1 AND role IS NOT 33",
&[&(owner as i64)], &[&(owner as isize)],
|x| { Self::get_membership_from_row(x) } |x| { Self::get_membership_from_row(x) }
); );

View file

@ -37,7 +37,7 @@ impl DataManager {
let res = query_rows!( let res = query_rows!(
&conn, &conn,
"SELECT * FROM notifications WHERE owner = $1", "SELECT * FROM notifications WHERE owner = $1",
&[&(owner as i64)], &[&(owner as isize)],
|x| { Self::get_notification_from_row(x) } |x| { Self::get_notification_from_row(x) }
); );

View file

@ -62,7 +62,11 @@ impl DataManager {
let res = query_rows!( let res = query_rows!(
&conn, &conn,
"SELECT * FROM posts WHERE replying_to = $1 ORDER BY created DESC LIMIT $2 OFFSET $3", "SELECT * FROM posts WHERE replying_to = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)], &[
&(id as isize),
&(batch as isize),
&((page * batch) as isize)
],
|x| { Self::get_post_from_row(x) } |x| { Self::get_post_from_row(x) }
); );
@ -125,7 +129,11 @@ impl DataManager {
let res = query_rows!( let res = query_rows!(
&conn, &conn,
"SELECT * FROM posts WHERE owner = $1 ORDER BY created DESC LIMIT $2 OFFSET $3", "SELECT * FROM posts WHERE owner = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)], &[
&(id as isize),
&(batch as isize),
&((page * batch) as isize)
],
|x| { Self::get_post_from_row(x) } |x| { Self::get_post_from_row(x) }
); );
@ -156,7 +164,83 @@ impl DataManager {
let res = query_rows!( let res = query_rows!(
&conn, &conn,
"SELECT * FROM posts WHERE community = $1 AND replying_to IS NULL ORDER BY created DESC LIMIT $2 OFFSET $3", "SELECT * FROM posts WHERE community = $1 AND replying_to IS NULL ORDER BY created DESC LIMIT $2 OFFSET $3",
&[&(id as i64), &(batch as i64), &((page * batch) as i64)], &[
&(id as isize),
&(batch as isize),
&((page * batch) as isize)
],
|x| { Self::get_post_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("post".to_string()));
}
Ok(res.unwrap())
}
/// Get posts from all communities, sorted by likes.
///
/// # Arguments
/// * `batch` - the limit of posts in each page
/// * `page` - the page number
pub async fn get_popular_posts(&self, batch: usize, page: usize) -> Result<Vec<Post>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM posts ORDER BY likes DESC, created ASC LIMIT $2 OFFSET $3",
&[&(batch as isize), &((page * batch) as isize)],
|x| { Self::get_post_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("post".to_string()));
}
Ok(res.unwrap())
}
/// Get posts from all communities the given user is in.
///
/// # Arguments
/// * `id` - the ID of the user
/// * `batch` - the limit of posts in each page
/// * `page` - the page number
pub async fn get_posts_from_user_communities(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<Post>> {
let memberships = self.get_memberships_by_owner(id).await?;
let mut memberships = memberships.iter();
let first = match memberships.next() {
Some(f) => f,
None => return Ok(Vec::new()),
};
let mut query_string: String = String::new();
for membership in memberships {
query_string.push_str(&format!(" OR community = {}", membership.community));
}
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
&format!(
"SELECT * FROM posts WHERE community = {} {query_string} ORDER BY created DESC LIMIT $1 OFFSET $2",
first.community
),
&[&(batch as isize), &((page * batch) as isize)],
|x| { Self::get_post_from_row(x) } |x| { Self::get_post_from_row(x) }
); );

View file

@ -46,7 +46,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM reactions WHERE owner = $1 AND asset = $2", "SELECT * FROM reactions WHERE owner = $1 AND asset = $2",
&[&(owner as i64), &(asset as i64)], &[&(owner as isize), &(asset as isize)],
|x| { Ok(Self::get_reaction_from_row(x)) } |x| { Ok(Self::get_reaction_from_row(x)) }
); );

View file

@ -39,7 +39,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM userblocks WHERE initiator = $1 AND receiver = $2", "SELECT * FROM userblocks WHERE initiator = $1 AND receiver = $2",
&[&(initiator as i64), &(receiver as i64)], &[&(initiator as isize), &(receiver as isize)],
|x| { Ok(Self::get_userblock_from_row(x)) } |x| { Ok(Self::get_userblock_from_row(x)) }
); );
@ -64,7 +64,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM userblocks WHERE receiver = $1 AND initiator = $2", "SELECT * FROM userblocks WHERE receiver = $1 AND initiator = $2",
&[&(receiver as i64), &(initiator as i64)], &[&(receiver as isize), &(initiator as isize)],
|x| { Ok(Self::get_userblock_from_row(x)) } |x| { Ok(Self::get_userblock_from_row(x)) }
); );

View file

@ -1,7 +1,7 @@
use super::*; use super::*;
use crate::cache::Cache; use crate::cache::Cache;
use crate::model::{Error, Result, auth::User, auth::UserFollow, permissions::FinePermission}; use crate::model::{Error, Result, auth::User, auth::UserFollow, permissions::FinePermission};
use crate::{auto_method, execute, get, query_row}; use crate::{auto_method, execute, get, query_row, query_rows};
#[cfg(feature = "sqlite")] #[cfg(feature = "sqlite")]
use rusqlite::Row; use rusqlite::Row;
@ -39,7 +39,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM userfollows WHERE initiator = $1 AND receiver = $2", "SELECT * FROM userfollows WHERE initiator = $1 AND receiver = $2",
&[&(initiator as i64), &(receiver as i64)], &[&(initiator as isize), &(receiver as isize)],
|x| { Ok(Self::get_userfollow_from_row(x)) } |x| { Ok(Self::get_userfollow_from_row(x)) }
); );
@ -64,7 +64,7 @@ impl DataManager {
let res = query_row!( let res = query_row!(
&conn, &conn,
"SELECT * FROM userfollows WHERE receiver = $1 AND initiator = $2", "SELECT * FROM userfollows WHERE receiver = $1 AND initiator = $2",
&[&(receiver as i64), &(initiator as i64)], &[&(receiver as isize), &(initiator as isize)],
|x| { Ok(Self::get_userfollow_from_row(x)) } |x| { Ok(Self::get_userfollow_from_row(x)) }
); );
@ -75,6 +75,76 @@ impl DataManager {
Ok(res.unwrap()) Ok(res.unwrap())
} }
/// Get users the given user is following.
///
/// # Arguments
/// * `id` - the ID of the user
/// * `batch` - the limit of userfollows in each page
/// * `page` - the page number
pub async fn get_userfollows_by_initiator(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<UserFollow>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM userfollows WHERE initiator = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[
&(id as isize),
&(batch as isize),
&((page * batch) as isize)
],
|x| { Self::get_userfollow_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("user follow".to_string()));
}
Ok(res.unwrap())
}
/// Get users following the given user.
///
/// # Arguments
/// * `id` - the ID of the user
/// * `batch` - the limit of userfollows in each page
/// * `page` - the page number
pub async fn get_userfollows_by_receiver(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<UserFollow>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM userfollows WHERE receiver = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[
&(id as isize),
&(batch as isize),
&((page * batch) as isize)
],
|x| { Self::get_userfollow_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("user follow".to_string()));
}
Ok(res.unwrap())
}
/// Create a new user follow in the database. /// Create a new user follow in the database.
/// ///
/// # Arguments /// # Arguments