Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
11.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

use crate::templates::components::pagination::pager_with_missing;

use crate::templates::components::report_category::{report_status, report_type};

use crate::{
    api::types::{ReportEntry, SearchReportsResponse},
    config::AdminConfig,
    templates::components::{
        media::{guild_icon_url, initials, user_avatar_url},
        page_container::card_with_header,
        report_category::{reason_repeats_category, report_category},
        report_webhook::{reported_webhook, webhook_identity},
        table::{table, table_body, table_container, table_head},
    },
    utils::{timestamps::format_admin_timestamp, user_tag::user_tag},
};
use maud::{Markup, html};

pub fn reports_tab(
    config: &AdminConfig,
    user_id: &str,
    sent: Option<&SearchReportsResponse>,
    received: Option<&SearchReportsResponse>,
    sent_page: u32,
    received_page: u32,
    limit: u32,
) -> Markup {
    let base = &config.base_path;
    html! {
        div class="space-y-6" {
            (report_section(
                config,
                base,
                user_id,
                "sent",
                "Reports Sent by User",
                "No reports sent by this user.",
                sent,
                sent_page,
                received_page,
                limit,
            ))
            (report_section(
                config,
                base,
                user_id,
                "received",
                "Reports Against User",
                "No reports against this user.",
                received,
                received_page,
                sent_page,
                limit,
            ))
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn report_section(
    config: &AdminConfig,
    base: &str,
    user_id: &str,
    kind: &str,
    title: &str,
    empty_msg: &str,
    data: Option<&SearchReportsResponse>,
    current_page: u32,
    other_page: u32,
    limit: u32,
) -> Markup {
    let (reports, total) = match data {
        Some(d) => (&d.reports, d.total),
        None => {
            return card_with_header(
                title,
                html! {
                    p class="text-sm text-neutral-500" {
                        "Failed to load reports."
                    }
                },
            );
        }
    };

    let offset = u64::from(current_page) * u64::from(limit);
    let has_previous = current_page > 0;
    let next_page = current_page
        .checked_add(1)
        .filter(|_| (reports.len() as u64) < total.saturating_sub(offset));

    let (sent_page, received_page) = if kind == "sent" {
        (current_page, other_page)
    } else {
        (other_page, current_page)
    };

    html! {
        (card_with_header(title, html! {
            div class="space-y-4" {
                p class="text-sm text-neutral-500" {
                    (total) " total"
                }

                @if reports.is_empty() {
                    p class="text-sm text-neutral-500" { (empty_msg) }
                } @else {
                    @let headers = if kind == "sent" {
                        vec!["Reported At", "Type / Category", "Reported Entity", "Status"]
                    } else {
                        vec!["Reported At", "Type / Category", "Reporter", "Status"]
                    };
                    (report_tab_table(
                        &headers,
                        html! {
                            @for report in reports {
                                (report_row(config, base, kind, report))
                            }
                        },
                    ))
                }

                @if has_previous || next_page.is_some() {
                    (pager_with_missing(has_previous.then(|| format!("{base}/users/{user_id}?tab=reports&reports_limit={limit}&reports_sent_page={}&reports_received_page={}", if kind == "sent" {current_page - 1} else {sent_page}, if kind == "received" {current_page - 1} else {received_page})), None, next_page.map(|page| format!("{base}/users/{user_id}?tab=reports&reports_limit={limit}&reports_sent_page={}&reports_received_page={}", if kind == "sent" {page} else {sent_page}, if kind == "received" {page} else {received_page})), true))
                }
            }
        }))
    }
}

pub(crate) fn tagged_user(
    global_name: Option<&str>,
    username: &str,
    discriminator: Option<&str>,
) -> Markup {
    let tag = user_tag(username, discriminator.unwrap_or("0000"), false);
    html! {
        @if let Some(name) = global_name.map(str::trim).filter(|name| !name.is_empty()) {
            (name) " "
            span class="whitespace-nowrap text-neutral-500 text-xs" { "(" (tag) ")" }
        } @else {
            span class="whitespace-nowrap" { (tag) }
        }
    }
}

pub(crate) fn reporter_label(report: &ReportEntry) -> Markup {
    if let Some(ref username) = report.reporter_username {
        return tagged_user(
            report.reporter_global_name.as_deref(),
            username,
            report.reporter_discriminator.as_deref(),
        );
    }
    if let Some(ref tag) = report.reporter_tag {
        return html! { span class="whitespace-nowrap" { (tag) } };
    }
    html! {
        (report
            .reporter_email
            .as_deref()
            .or(report.reporter_id.as_deref())
            .unwrap_or("Unknown reporter"))
    }
}

pub(crate) fn report_tab_table(headers: &[&str], rows: Markup) -> Markup {
    let has_actions = headers.last() == Some(&"Actions");
    html! {
        (table_container(table(html! {
            (table_head(html! {
                tr {
                    @for (index, header) in headers.iter().enumerate() {
                        @let folded = index == 1 || (has_actions && *header == "Status");
                        th class={"px-2 py-3 text-left text-neutral-600 text-xs uppercase tracking-wider xl:px-4" (if folded { " hidden whitespace-nowrap xl:table-cell" } else { " whitespace-nowrap" })} {
                            @if has_actions && index + 1 == headers.len() {
                                span class="xl:hidden" { "Status / " }
                            }
                            (header)
                        }
                    }
                }
            }))
            (table_body(rows))
        })))
    }
}

pub(crate) fn reported_at_cell(base: &str, report: &ReportEntry) -> Markup {
    html! {
        td class="px-2 py-3 text-sm text-neutral-900 xl:px-3" {
            div { (format_admin_timestamp(&report.reported_at)) }
            a href={(base) "/reports/" (report.report_id)}
                class="whitespace-nowrap font-mono text-blue-600 text-xs tracking-tight hover:underline" {
                (report.report_id)
            }
            div class="mt-1 xl:hidden" data-report-type-compact=(report.report_id) {
                (type_and_category_lines(report))
            }
        }
    }
}

pub(crate) fn type_and_category_cell(report: &ReportEntry) -> Markup {
    html! {
        td class="hidden px-4 py-3 text-sm text-neutral-900 xl:table-cell" {
            (type_and_category_lines(report))
        }
    }
}

fn type_and_category_lines(report: &ReportEntry) -> Markup {
    let reason_label = report
        .reason
        .as_deref()
        .map(|reason| report.reason_label.as_deref().unwrap_or(reason));
    let repeats = report
        .category
        .as_deref()
        .zip(reason_label)
        .is_some_and(|(category, label)| reason_repeats_category(category, label));
    html! {
        div class="text-neutral-500 text-xs" { (report_type(report.report_type).0) }
        @if let Some(category) = &report.category {
            div class="break-words" data-report-reason=[report.reason.as_deref().filter(|_| repeats)] {
                (report_category(category))
            }
        }
        @if !repeats && let (Some(reason), Some(label)) = (&report.reason, reason_label) {
            div class="break-words text-neutral-500 text-xs" data-report-reason=(reason) {
                (label)
            }
        }
    }
}

fn report_row(config: &AdminConfig, base: &str, kind: &str, report: &ReportEntry) -> Markup {
    let webhook = if kind == "sent" {
        reported_webhook(config, report)
    } else {
        None
    };

    let entity_href = if kind == "sent" {
        report
            .reported_user_id
            .as_ref()
            .map(|id| format!("{base}/users/{id}"))
            .or_else(|| {
                report
                    .reported_guild_id
                    .as_ref()
                    .map(|id| format!("{base}/guilds/{id}"))
            })
    } else {
        report
            .reporter_id
            .as_ref()
            .map(|id| format!("{base}/users/{id}"))
    };

    let entity_display = if kind == "sent" {
        format_reported_entity(report)
    } else {
        reporter_label(report)
    };

    html! {
        tr class="hover:bg-neutral-50 transition-colors" {
            (reported_at_cell(base, report))
            (type_and_category_cell(report))
            td class="px-2 py-3 text-sm [overflow-wrap:anywhere] [&_.whitespace-nowrap]:whitespace-normal xl:px-4 xl:[&_.whitespace-nowrap]:whitespace-nowrap" {
                @if let Some(webhook) = &webhook {
                    a href=(webhook.reports_href) class="hover:underline" {
                        (webhook_identity(webhook))
                    }
                } @else if let Some(href) = entity_href {
                    a href=(href)
                        class="inline-flex items-center gap-2 hover:underline" {
                        @if kind == "sent" {
                            (reported_entity_icon(config, report))
                        }
                        span class="min-w-0" { (entity_display) }
                    }
                } @else {
                    span { (entity_display) }
                }
            }
            td class="whitespace-nowrap px-2 py-3 text-sm text-neutral-900 xl:px-4" {
                (report_status(report.status).0)
            }
        }
    }
}

fn format_reported_entity(report: &ReportEntry) -> Markup {
    if let Some(ref username) = report.reported_user_username {
        return tagged_user(
            report.reported_user_global_name.as_deref(),
            username,
            report.reported_user_discriminator.as_deref(),
        );
    }
    if let Some(ref tag) = report.reported_user_tag {
        return html! { span class="whitespace-nowrap" { (tag) } };
    }
    html! {
        (report
            .reported_user_id
            .as_ref()
            .or(report.reported_guild_name.as_ref())
            .or(report.reported_guild_id.as_ref())
            .map_or("Unknown", String::as_str))
    }
}

fn reported_entity_icon(config: &AdminConfig, report: &ReportEntry) -> Markup {
    if let Some(ref user_id) = report.reported_user_id {
        return html! {
            img
                src=(user_avatar_url(config, user_id, report.reported_user_avatar_hash.as_deref(), 80, true))
                alt=""
                class="h-8 w-8 flex-shrink-0 rounded-full object-cover";
        };
    }
    if let Some(ref guild_id) = report.reported_guild_id {
        if let Some(url) = guild_icon_url(
            config,
            guild_id,
            report.reported_guild_icon_hash.as_deref(),
            80,
            true,
        ) {
            return html! {
                img src=(url) alt="" class="h-8 w-8 flex-shrink-0 rounded-full object-cover";
            };
        }
        return html! {
            span class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-neutral-200 text-neutral-600 text-xs" {
                (initials(report.reported_guild_name.as_deref().unwrap_or(guild_id)))
            }
        };
    }
    html! {}
}