Merge pull request #399 from EdouardVanbelle/feat/implement-cursor-on-main-lists
This commit is contained in:
@@ -1,10 +1,14 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// DTO for favorites item, enriched with item metadata via SQL JOIN
|
||||
/// so the frontend does not need N+1 requests to resolve names/sizes.
|
||||
@@ -104,6 +108,120 @@ pub struct BatchFavoritesResult {
|
||||
pub favorites: Vec<FavoriteItemDto>,
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// Cursor-paginated favorites resources (GET /api/favorites/resources)
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Raw row returned by the UNION ALL query that joins `auth.user_favorites`
|
||||
/// with `storage.files` / `storage.folders`. Never serialised directly.
|
||||
pub struct FavoriteResourceRow {
|
||||
pub resource_type: String, // "file" | "folder"
|
||||
pub resource_id: Uuid,
|
||||
pub name: String,
|
||||
pub parent_id: Option<Uuid>,
|
||||
pub mime_type: Option<String>,
|
||||
/// `-1` for folders, actual byte-count for files.
|
||||
pub size: i64,
|
||||
pub resource_created_at: DateTime<Utc>,
|
||||
pub modified_at: DateTime<Utc>,
|
||||
pub owner_id: Uuid,
|
||||
/// `true` when `owner_id == requesting user_id`.
|
||||
pub is_owner: bool,
|
||||
pub favorited_at: DateTime<Utc>,
|
||||
/// Human-readable path (e.g. `Documents/Work` for a folder,
|
||||
/// `Documents/Work/report.pdf` for a file). Always populated; the
|
||||
/// handler clears it to `""` when `is_owner` is false.
|
||||
pub path: Option<String>,
|
||||
// Pre-computed sort fields for cursor construction.
|
||||
pub sort_str: Option<String>,
|
||||
pub sort_int: Option<i64>,
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Opaque keyset-pagination cursor for `GET /api/favorites/resources`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FavoritesCursor {
|
||||
/// Sort dimension active when this cursor was produced.
|
||||
/// Values: `"name"` (default), `"type"`, `"favorited_at"`, `"modified_at"`,
|
||||
/// `"size"`, `"owner"`.
|
||||
#[serde(default = "FavoritesCursor::default_order")]
|
||||
pub order_by: String,
|
||||
/// UUID of the last item on the previous page (tie-breaker).
|
||||
pub resource_id: Uuid,
|
||||
/// `LOWER(name)` for `name`/`type` sorts; `LOWER(username)` for `owner`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_str: Option<String>,
|
||||
/// Multipurpose integer: `folder_first` for `name`, `type_order` for `type`,
|
||||
/// size in bytes for `size`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_int: Option<i64>,
|
||||
/// Timestamp for `favorited_at` and `modified_at` sorts.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
/// Whether the result set was reversed — must match on every page.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl FavoritesCursor {
|
||||
fn default_order() -> String {
|
||||
"name".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl PageCursor for FavoritesCursor {}
|
||||
|
||||
/// Query parameters for `GET /api/favorites/resources`.
|
||||
#[derive(Debug, Deserialize, IntoParams)]
|
||||
pub struct FavoritesResourcesQuery {
|
||||
/// Maximum items per page (1–200, default 50).
|
||||
#[serde(default = "CursorQuery::default_limit")]
|
||||
pub limit: u32,
|
||||
/// Opaque cursor from a previous response. Omit to start from the first page.
|
||||
pub cursor: Option<String>,
|
||||
/// Sort / group-by dimension. Supported: `"name"` (default), `"type"`,
|
||||
/// `"favorited_at"`, `"modified_at"`, `"size"`, `"owner"`.
|
||||
pub order_by: Option<String>,
|
||||
/// Comma-separated resource types to include, e.g. `"file,folder"`.
|
||||
/// Omit to include both.
|
||||
pub resource_types: Option<String>,
|
||||
/// Reverse the sort order. Default `false`.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl FavoritesResourcesQuery {
|
||||
pub fn limit_clamped(&self) -> usize {
|
||||
self.limit.clamp(1, 200) as usize
|
||||
}
|
||||
|
||||
pub fn decode_cursor(&self) -> Option<FavoritesCursor> {
|
||||
self.cursor.as_deref().and_then(FavoritesCursor::decode)
|
||||
}
|
||||
|
||||
/// Returns `None` when `resource_types` is absent (= include all).
|
||||
pub fn resource_kinds(&self) -> Option<Vec<ResourceKind>> {
|
||||
self.resource_types.as_deref().map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|t| ResourceKind::parse(t.trim()))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One item in a `GET /api/favorites/resources` page.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct FavoritesResourceItemDto {
|
||||
pub resource_type: ResourceTypeDto,
|
||||
/// When the resource was added to the user's favorites.
|
||||
pub favorited_at: DateTime<Utc>,
|
||||
/// Full resource details — shape determined by `resource_type`.
|
||||
pub resource: ResourceContentDto,
|
||||
}
|
||||
|
||||
/// Response envelope for `GET /api/favorites/resources`.
|
||||
pub type FavoritesResourcesDto = CursorListResponse<FavoritesResourceItemDto>;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct BatchFavoritesStats {
|
||||
/// How many items were requested
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::application::dtos::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use crate::application::dtos::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::entities::folder::Folder;
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// DTO for folder creation requests
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
@@ -145,3 +150,138 @@ impl Default for FolderDto {
|
||||
Self::empty()
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// Cursor-paginated folder resources (GET /api/folders/{id}/resources)
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Raw row returned by the UNION ALL query that combines `storage.folders` and
|
||||
/// `storage.files` for a given parent folder. Used internally between the
|
||||
/// repository and service/handler layers — never serialised directly.
|
||||
pub struct FolderResourceRow {
|
||||
pub resource_type: String, // "folder" | "file"
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
/// Parent folder UUID (for both resource types).
|
||||
pub parent_id: Option<Uuid>,
|
||||
/// `None` for folders.
|
||||
pub mime_type: Option<String>,
|
||||
/// `-1` sentinel for folders (no physical size).
|
||||
pub size: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub modified_at: DateTime<Utc>,
|
||||
pub owner_id: Uuid,
|
||||
// Pre-computed sort fields — returned by the SQL for cursor construction.
|
||||
/// `LOWER(name)` used by `name`/`type` sorts.
|
||||
pub sort_str: String,
|
||||
/// `category_order` for files, `0` for folders.
|
||||
pub type_order: i64,
|
||||
/// `0` for folders, `1` for files (used by `name` sort to keep folders first).
|
||||
pub folder_first: i32,
|
||||
}
|
||||
|
||||
/// Opaque keyset-pagination cursor for `/api/folders/{id}/resources`.
|
||||
///
|
||||
/// Encoded as base64url-JSON (same scheme as [`GrantCursor`]).
|
||||
/// Fields are sparse: only the sort-relevant ones are serialised.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FolderResourceCursor {
|
||||
/// Sort dimension active when this cursor was produced.
|
||||
#[serde(default = "FolderResourceCursor::default_order")]
|
||||
pub order_by: String,
|
||||
/// UUID of the last item on the previous page (tie-breaker).
|
||||
pub resource_id: Uuid,
|
||||
/// `LOWER(name)` for `name`/`type` sorts.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_str: Option<String>,
|
||||
/// Multipurpose integer sort key:
|
||||
/// - `name`: `folder_first` (0 = folder, 1 = file)
|
||||
/// - `type`: `category_order` (0 = Folder, 100 = Image …)
|
||||
/// - `size`: file size in bytes, -1 for folders
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_int: Option<i64>,
|
||||
/// Timestamp for `modified_at` / `created_at` sorts.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
/// Whether the result set was reversed when this cursor was produced.
|
||||
/// Must be passed unchanged on subsequent page requests.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl FolderResourceCursor {
|
||||
fn default_order() -> String {
|
||||
"name".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl PageCursor for FolderResourceCursor {}
|
||||
|
||||
/// Query parameters for `GET /api/folders/{id}/resources`.
|
||||
#[derive(Debug, Deserialize, IntoParams)]
|
||||
pub struct FolderResourcesQuery {
|
||||
/// Maximum items per page (1–200, default 50).
|
||||
#[serde(default = "CursorQuery::default_limit")]
|
||||
pub limit: u32,
|
||||
/// Opaque cursor from a previous response. Omit to start from the top.
|
||||
pub cursor: Option<String>,
|
||||
/// Sort / group-by dimension. Supported: `"name"` (default), `"type"`,
|
||||
/// `"modified_at"`, `"created_at"`, `"size"`.
|
||||
pub order_by: Option<String>,
|
||||
/// Comma-separated resource types to include, e.g. `"file,folder"`.
|
||||
/// Omit to include both.
|
||||
pub resource_types: Option<String>,
|
||||
/// Reverse the sort order. Default `false` (normal order).
|
||||
/// Must be the same on all pages of the same result set — the cursor
|
||||
/// carries this flag so the server can validate consistency.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl FolderResourcesQuery {
|
||||
/// Returns `limit` clamped to `[1, 200]`.
|
||||
pub fn limit_clamped(&self) -> usize {
|
||||
self.limit.clamp(1, 200) as usize
|
||||
}
|
||||
|
||||
/// Decode the optional cursor string. Invalid cursor → start from top.
|
||||
pub fn decode_cursor(&self) -> Option<FolderResourceCursor> {
|
||||
self.cursor
|
||||
.as_deref()
|
||||
.and_then(FolderResourceCursor::decode)
|
||||
}
|
||||
|
||||
/// Parse `resource_types` into a `Vec<ResourceKind>`.
|
||||
/// Returns `None` when the field is absent (= include all types).
|
||||
pub fn resource_kinds(&self) -> Option<Vec<ResourceKind>> {
|
||||
self.resource_types.as_deref().map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|t| ResourceKind::parse(t.trim()))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for [`FolderService::list_resources_paged_with_perms`].
|
||||
///
|
||||
/// Groups the optional parameters so the function stays within clippy's
|
||||
/// `too_many_arguments` limit while remaining easy to extend.
|
||||
pub struct ListResourcesOptions<'a> {
|
||||
pub limit: usize,
|
||||
pub cursor: Option<FolderResourceCursor>,
|
||||
pub order_by: &'a str,
|
||||
pub kinds: Option<&'a [ResourceKind]>,
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
/// One item in a `/resources` page — a file or folder with a `resource_type` tag.
|
||||
/// Re-uses [`ResourceContentDto`] so the shape is identical to `SharedWithMeItemDto.resource`.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct FolderResourceItemDto {
|
||||
pub resource_type: ResourceTypeDto,
|
||||
/// Full resource details. Shape is determined by `resource_type`.
|
||||
pub resource: ResourceContentDto,
|
||||
}
|
||||
|
||||
/// Response envelope for `GET /api/folders/{id}/resources`.
|
||||
pub type FolderResourcesDto = CursorListResponse<FolderResourceItemDto>;
|
||||
|
||||
@@ -252,6 +252,11 @@ pub struct SharedWithMeQuery {
|
||||
/// Comma-separated resource types to include, e.g. `file,folder`.
|
||||
/// Omit to return all known types.
|
||||
pub resource_types: Option<String>,
|
||||
/// Reverse the sort order. Default `false` (normal order).
|
||||
/// Must be the same on all pages of the same result set — the cursor
|
||||
/// carries this flag so the server can validate consistency.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl SharedWithMeQuery {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// DTO for recent items, enriched with item metadata via SQL JOIN
|
||||
/// so the frontend does not need N+1 requests to resolve names/sizes.
|
||||
@@ -84,3 +88,109 @@ impl RecentItemDto {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// Cursor-paginated recent resources (GET /api/recent/resources)
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Raw row returned by the UNION ALL query for `/api/recent/resources`.
|
||||
pub struct RecentResourceRow {
|
||||
pub resource_type: String, // "file" | "folder"
|
||||
pub resource_id: Uuid,
|
||||
pub name: String,
|
||||
pub parent_id: Option<Uuid>,
|
||||
pub mime_type: Option<String>,
|
||||
/// `-1` for folders, actual byte-count for files.
|
||||
pub size: i64,
|
||||
pub resource_created_at: DateTime<Utc>,
|
||||
pub modified_at: DateTime<Utc>,
|
||||
pub owner_id: Uuid,
|
||||
/// `true` when `owner_id == requesting user_id`.
|
||||
pub is_owner: bool,
|
||||
pub accessed_at: DateTime<Utc>,
|
||||
/// Human-readable path. Always populated in the row; the handler clears it
|
||||
/// to `""` when `is_owner` is false.
|
||||
pub path: Option<String>,
|
||||
// Pre-computed sort fields for cursor construction.
|
||||
pub sort_str: Option<String>,
|
||||
pub sort_int: Option<i64>,
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Opaque keyset-pagination cursor for `GET /api/recent/resources`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecentCursor {
|
||||
/// Sort dimension active when this cursor was produced.
|
||||
/// Values: `"accessed_at"` (default), `"name"`, `"type"`, `"modified_at"`, `"size"`, `"owner"`.
|
||||
#[serde(default = "RecentCursor::default_order")]
|
||||
pub order_by: String,
|
||||
/// UUID of the last item on the previous page (tie-breaker).
|
||||
pub resource_id: Uuid,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_str: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_int: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl RecentCursor {
|
||||
fn default_order() -> String {
|
||||
"accessed_at".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl PageCursor for RecentCursor {}
|
||||
|
||||
/// Query parameters for `GET /api/recent/resources`.
|
||||
#[derive(Debug, Deserialize, IntoParams)]
|
||||
pub struct RecentResourcesQuery {
|
||||
/// Maximum items per page (1–200, default 50).
|
||||
#[serde(default = "CursorQuery::default_limit")]
|
||||
pub limit: u32,
|
||||
/// Opaque cursor from a previous response. Omit to start from the first page.
|
||||
pub cursor: Option<String>,
|
||||
/// Sort / group-by dimension. Supported: `"accessed_at"` (default), `"name"`,
|
||||
/// `"type"`, `"modified_at"`, `"size"`, `"owner"`.
|
||||
pub order_by: Option<String>,
|
||||
/// Comma-separated resource types to include, e.g. `"file,folder"`.
|
||||
/// Omit to include both.
|
||||
pub resource_types: Option<String>,
|
||||
/// Reverse the sort order. Default `false`.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl RecentResourcesQuery {
|
||||
pub fn limit_clamped(&self) -> usize {
|
||||
self.limit.clamp(1, 200) as usize
|
||||
}
|
||||
|
||||
pub fn decode_cursor(&self) -> Option<RecentCursor> {
|
||||
self.cursor.as_deref().and_then(RecentCursor::decode)
|
||||
}
|
||||
|
||||
/// Returns `None` when `resource_types` is absent (= include all).
|
||||
pub fn resource_kinds(&self) -> Option<Vec<ResourceKind>> {
|
||||
self.resource_types.as_deref().map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|t| ResourceKind::parse(t.trim()))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One item in a `GET /api/recent/resources` page.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct RecentResourceItemDto {
|
||||
pub resource_type: ResourceTypeDto,
|
||||
/// When the resource was last accessed.
|
||||
pub accessed_at: DateTime<Utc>,
|
||||
/// Full resource details — shape determined by `resource_type`.
|
||||
pub resource: ResourceContentDto,
|
||||
}
|
||||
|
||||
/// Response envelope for `GET /api/recent/resources`.
|
||||
pub type RecentResourcesDto = CursorListResponse<RecentResourceItemDto>;
|
||||
|
||||
@@ -86,6 +86,7 @@ pub trait AuthorizationEngine: Send + Sync + 'static {
|
||||
limit: u32,
|
||||
cursor: Option<GrantCursor>,
|
||||
sort_by: &str,
|
||||
reverse: bool,
|
||||
) -> Result<(Vec<IncomingGrantSummary>, Option<GrantCursor>), DomainError>;
|
||||
|
||||
/// All grants on a specific resource (for "Manage sharing" UI). Caller
|
||||
|
||||
@@ -2,8 +2,11 @@ use std::collections::HashSet;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::favorites_dto::{BatchFavoritesResult, FavoriteItemDto};
|
||||
use crate::application::dtos::favorites_dto::{
|
||||
BatchFavoritesResult, FavoriteItemDto, FavoriteResourceRow, FavoritesCursor,
|
||||
};
|
||||
use crate::common::errors::Result;
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// Defines operations for managing user favorites
|
||||
pub trait FavoritesUseCase: Send + Sync {
|
||||
@@ -74,4 +77,17 @@ pub trait FavoritesRepositoryPort: Send + Sync + 'static {
|
||||
user_id: Uuid,
|
||||
item_ids: &[(&str, &str)], // (item_id, item_type) pairs
|
||||
) -> Result<HashSet<String>>;
|
||||
|
||||
/// Cursor-paginated list of a user's favorited resources.
|
||||
/// Items that no longer exist (deleted/trashed) are silently excluded.
|
||||
/// `kinds = None` → both files and folders.
|
||||
async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&FavoritesCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<FavoriteResourceRow>>;
|
||||
}
|
||||
|
||||
@@ -51,4 +51,15 @@ pub trait RecentItemsRepositoryPort: Send + Sync + 'static {
|
||||
|
||||
/// Removes items exceeding `max_items` (the oldest ones).
|
||||
async fn prune(&self, user_id: Uuid, max_items: i32) -> Result<()>;
|
||||
|
||||
/// List recent items with cursor pagination, sorting, and optional type filter.
|
||||
async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&crate::application::dtos::recent_dto::RecentCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[crate::domain::services::authorization::ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<crate::application::dtos::recent_dto::RecentResourceRow>>;
|
||||
}
|
||||
|
||||
@@ -4,11 +4,14 @@ use std::sync::Arc;
|
||||
use tracing::info;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::cursor::PageCursor;
|
||||
use crate::application::dtos::favorites_dto::{
|
||||
BatchFavoritesResult, BatchFavoritesStats, FavoriteItemDto,
|
||||
BatchFavoritesResult, BatchFavoritesStats, FavoriteItemDto, FavoriteResourceRow,
|
||||
FavoritesCursor,
|
||||
};
|
||||
use crate::application::ports::favorites_ports::{FavoritesRepositoryPort, FavoritesUseCase};
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
use crate::infrastructure::repositories::pg::FavoritesPgRepository;
|
||||
|
||||
/// Implementation of the FavoritesUseCase for managing user favorites.
|
||||
@@ -155,3 +158,105 @@ impl FavoritesUseCase for FavoritesService {
|
||||
self.repo.batch_check_favorites(user_id, item_ids).await
|
||||
}
|
||||
}
|
||||
|
||||
impl FavoritesService {
|
||||
/// Cursor-paginated list of the user's favorited resources.
|
||||
///
|
||||
/// No authz needed — favorites are strictly user-scoped; the repository
|
||||
/// enforces `WHERE user_id = $1` so users can only see their own entries.
|
||||
///
|
||||
/// Returns `(rows, next_cursor_encoded)`.
|
||||
pub async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<FavoritesCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<(Vec<FavoriteResourceRow>, Option<String>)> {
|
||||
// Fetch one extra row to detect whether a next page exists.
|
||||
let mut rows = self
|
||||
.repo
|
||||
.list_resources_paged(
|
||||
user_id,
|
||||
limit + 1,
|
||||
cursor.as_ref(),
|
||||
order_by,
|
||||
kinds,
|
||||
reverse,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let next_cursor = if rows.len() > limit {
|
||||
let last = &rows[limit - 1];
|
||||
let c = build_favorites_cursor(last, order_by, reverse);
|
||||
rows.truncate(limit);
|
||||
Some(c.encode())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok((rows, next_cursor))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the next-page cursor from the last row of the current page.
|
||||
/// `reverse` is stored in the cursor so subsequent pages use the same direction.
|
||||
fn build_favorites_cursor(
|
||||
row: &FavoriteResourceRow,
|
||||
order_by: &str,
|
||||
reverse: bool,
|
||||
) -> FavoritesCursor {
|
||||
match order_by {
|
||||
"type" => FavoritesCursor {
|
||||
order_by: "type".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(name)
|
||||
sort_int: row.sort_int, // type_order
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"favorited_at" => FavoritesCursor {
|
||||
order_by: "favorited_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // favorited_at timestamp
|
||||
reverse,
|
||||
},
|
||||
"modified_at" => FavoritesCursor {
|
||||
order_by: "modified_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // modified_at timestamp
|
||||
reverse,
|
||||
},
|
||||
"size" => FavoritesCursor {
|
||||
order_by: "size".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: row.sort_int, // file size in bytes
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"owner" => FavoritesCursor {
|
||||
order_by: "owner".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(username)
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // favorited_at (secondary sort)
|
||||
reverse,
|
||||
},
|
||||
_ => FavoritesCursor {
|
||||
// "name" (default): sort_str = LOWER(name), sort_int = folder_first (0 = folder, 1 = file)
|
||||
order_by: "name".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(),
|
||||
sort_int: row.sort_int, // folder_first
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::application::dtos::cursor::PageCursor;
|
||||
use crate::application::dtos::folder_dto::{
|
||||
CreateFolderDto, FolderDto, MoveFolderDto, RenameFolderDto,
|
||||
CreateFolderDto, FolderDto, FolderResourceCursor, FolderResourceRow, ListResourcesOptions,
|
||||
MoveFolderDto, RenameFolderDto,
|
||||
};
|
||||
use crate::application::ports::authorization_ports::AuthorizationEngine;
|
||||
use crate::application::ports::folder_ports::FolderUseCase;
|
||||
@@ -582,3 +584,109 @@ impl FolderUseCase for FolderService {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── FolderService — cursor-paginated resource listing ────────────────────────
|
||||
|
||||
impl FolderService {
|
||||
/// Cursor-paginated listing of sub-folders **and** files inside `parent_id`.
|
||||
///
|
||||
/// Enforces `Permission::Read` on the parent folder before querying.
|
||||
/// `order_by` controls both the SQL `ORDER BY` and the cursor encoding.
|
||||
/// `kinds` filters the result to only the specified resource types.
|
||||
pub async fn list_resources_paged_with_perms(
|
||||
&self,
|
||||
parent_id: &str,
|
||||
caller_id: Uuid,
|
||||
opts: ListResourcesOptions<'_>,
|
||||
) -> Result<(Vec<FolderResourceRow>, Option<String>), DomainError> {
|
||||
// 1. AuthZ — same check as list_folders_with_perms
|
||||
self.authz
|
||||
.require(
|
||||
Subject::User(caller_id),
|
||||
Permission::Read,
|
||||
Self::folder_resource(parent_id)?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let pid =
|
||||
Uuid::parse_str(parent_id).map_err(|_| DomainError::not_found("Folder", parent_id))?;
|
||||
|
||||
let ListResourcesOptions {
|
||||
limit,
|
||||
cursor,
|
||||
order_by,
|
||||
kinds,
|
||||
reverse,
|
||||
} = opts;
|
||||
|
||||
// 2. Fetch limit+1 rows so we can detect has_next
|
||||
let mut rows = self
|
||||
.folder_storage
|
||||
.list_resources_paged(pid, limit + 1, cursor.as_ref(), order_by, kinds, reverse)
|
||||
.await?;
|
||||
|
||||
// 3. Detect has_next, build encoded next cursor
|
||||
let next_cursor = if rows.len() > limit {
|
||||
let last = &rows[limit - 1];
|
||||
let c = build_folder_resource_cursor(last, order_by, reverse);
|
||||
rows.truncate(limit);
|
||||
Some(c.encode())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok((rows, next_cursor))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the next-page cursor from the last row of the current page.
|
||||
/// `reverse` is stored in the cursor so subsequent pages use the same order.
|
||||
fn build_folder_resource_cursor(
|
||||
row: &FolderResourceRow,
|
||||
order_by: &str,
|
||||
reverse: bool,
|
||||
) -> FolderResourceCursor {
|
||||
match order_by {
|
||||
"type" => FolderResourceCursor {
|
||||
order_by: "type".to_owned(),
|
||||
resource_id: row.id,
|
||||
sort_str: Some(row.sort_str.clone()),
|
||||
sort_int: Some(row.type_order),
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"modified_at" => FolderResourceCursor {
|
||||
order_by: "modified_at".to_owned(),
|
||||
resource_id: row.id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: Some(row.modified_at),
|
||||
reverse,
|
||||
},
|
||||
"created_at" => FolderResourceCursor {
|
||||
order_by: "created_at".to_owned(),
|
||||
resource_id: row.id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: Some(row.created_at),
|
||||
reverse,
|
||||
},
|
||||
"size" => FolderResourceCursor {
|
||||
order_by: "size".to_owned(),
|
||||
resource_id: row.id,
|
||||
sort_str: None,
|
||||
sort_int: Some(row.size),
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
_ => FolderResourceCursor {
|
||||
// "name" (default): sort_int = folder_first (0 or 1)
|
||||
order_by: "name".to_owned(),
|
||||
resource_id: row.id,
|
||||
sort_str: Some(row.sort_str.clone()),
|
||||
sort_int: Some(i64::from(row.folder_first)),
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::application::dtos::recent_dto::RecentItemDto;
|
||||
use crate::application::dtos::cursor::PageCursor;
|
||||
use crate::application::dtos::recent_dto::{RecentCursor, RecentItemDto, RecentResourceRow};
|
||||
use crate::application::ports::recent_ports::{RecentItemsRepositoryPort, RecentItemsUseCase};
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
use crate::infrastructure::repositories::pg::RecentItemsPgRepository;
|
||||
use std::sync::Arc;
|
||||
use tracing::info;
|
||||
@@ -109,3 +111,99 @@ impl RecentItemsUseCase for RecentService {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RecentService {
|
||||
/// No authz needed — recent items are strictly user-scoped; the repository
|
||||
/// enforces `WHERE user_id = $1` so users can only see their own entries.
|
||||
///
|
||||
/// Returns `(rows, next_cursor_encoded)`.
|
||||
pub async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<RecentCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<(Vec<RecentResourceRow>, Option<String>)> {
|
||||
// Fetch one extra row to detect whether a next page exists.
|
||||
let mut rows = self
|
||||
.repo
|
||||
.list_resources_paged(
|
||||
user_id,
|
||||
limit + 1,
|
||||
cursor.as_ref(),
|
||||
order_by,
|
||||
kinds,
|
||||
reverse,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let next_cursor = if rows.len() > limit {
|
||||
let last = &rows[limit - 1];
|
||||
let c = build_recent_cursor(last, order_by, reverse);
|
||||
rows.truncate(limit);
|
||||
Some(c.encode())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok((rows, next_cursor))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the next-page cursor from the last row of the current page.
|
||||
/// `reverse` is stored in the cursor so subsequent pages use the same direction.
|
||||
fn build_recent_cursor(row: &RecentResourceRow, order_by: &str, reverse: bool) -> RecentCursor {
|
||||
match order_by {
|
||||
"name" => RecentCursor {
|
||||
order_by: "name".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(name)
|
||||
sort_int: row.sort_int, // folder_first
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"type" => RecentCursor {
|
||||
order_by: "type".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(name)
|
||||
sort_int: row.sort_int, // type_order
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"modified_at" => RecentCursor {
|
||||
order_by: "modified_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // modified_at timestamp
|
||||
reverse,
|
||||
},
|
||||
"size" => RecentCursor {
|
||||
order_by: "size".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: row.sort_int, // size in bytes
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"owner" => RecentCursor {
|
||||
order_by: "owner".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(username)
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // accessed_at timestamp (secondary)
|
||||
reverse,
|
||||
},
|
||||
_ => RecentCursor {
|
||||
// default: accessed_at DESC
|
||||
order_by: "accessed_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // accessed_at timestamp
|
||||
reverse,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,6 +285,10 @@ pub struct GrantCursor {
|
||||
/// - `"size"` — file size in bytes (-1 = Folder sentinel)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_int: Option<i64>,
|
||||
/// Whether the result set was reversed when this cursor was produced.
|
||||
/// Must be passed unchanged on subsequent page requests.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl GrantCursor {
|
||||
|
||||
@@ -4,9 +4,12 @@ use std::sync::Arc;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::favorites_dto::FavoriteItemDto;
|
||||
use crate::application::dtos::favorites_dto::{
|
||||
FavoriteItemDto, FavoriteResourceRow, FavoritesCursor,
|
||||
};
|
||||
use crate::application::ports::favorites_ports::FavoritesRepositoryPort;
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// PostgreSQL implementation of the favorites persistence port.
|
||||
pub struct FavoritesPgRepository {
|
||||
@@ -279,4 +282,308 @@ impl FavoritesRepositoryPort for FavoritesPgRepository {
|
||||
|
||||
Ok(rows.iter().map(|r| r.get::<String, _>("item_id")).collect())
|
||||
}
|
||||
|
||||
async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&FavoritesCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<FavoriteResourceRow>> {
|
||||
let include_folders =
|
||||
kinds.is_none_or(|k| k.iter().any(|r| matches!(r, ResourceKind::Folder)));
|
||||
let include_files = kinds.is_none_or(|k| k.iter().any(|r| matches!(r, ResourceKind::File)));
|
||||
|
||||
// ── Build the UNION ALL CTE ─────────────────────────────────────────
|
||||
let mut cte_branches: Vec<&str> = Vec::new();
|
||||
|
||||
let folder_branch = r#"
|
||||
SELECT
|
||||
'folder'::text AS resource_type,
|
||||
fld.id AS resource_id,
|
||||
fld.name,
|
||||
fld.parent_id,
|
||||
NULL::text AS mime_type,
|
||||
-1::bigint AS size,
|
||||
fld.created_at AS resource_created_at,
|
||||
fld.updated_at AS modified_at,
|
||||
fld.user_id AS owner_id,
|
||||
(fld.user_id = $1::uuid) AS is_owner,
|
||||
uf.created_at AS favorited_at,
|
||||
fld.path::text AS resource_path,
|
||||
LOWER(fld.name) AS sort_str,
|
||||
0::bigint AS type_order,
|
||||
0::int AS folder_first
|
||||
FROM auth.user_favorites uf
|
||||
INNER JOIN storage.folders fld
|
||||
ON fld.id = uf.item_id::UUID AND NOT fld.is_trashed
|
||||
WHERE uf.user_id = $1::uuid AND uf.item_type = 'folder'"#;
|
||||
|
||||
let file_branch = r#"
|
||||
SELECT
|
||||
'file'::text AS resource_type,
|
||||
f.id AS resource_id,
|
||||
f.name,
|
||||
f.folder_id AS parent_id,
|
||||
f.mime_type,
|
||||
f.size::bigint,
|
||||
f.created_at AS resource_created_at,
|
||||
f.updated_at AS modified_at,
|
||||
f.user_id AS owner_id,
|
||||
(f.user_id = $1::uuid) AS is_owner,
|
||||
uf.created_at AS favorited_at,
|
||||
COALESCE(pfld.path::text || '/' || f.name, f.name) AS resource_path,
|
||||
LOWER(f.name) AS sort_str,
|
||||
f.category_order::bigint AS type_order,
|
||||
1::int AS folder_first
|
||||
FROM auth.user_favorites uf
|
||||
INNER JOIN storage.files f
|
||||
ON f.id = uf.item_id::UUID AND NOT f.is_trashed
|
||||
LEFT JOIN storage.folders pfld
|
||||
ON pfld.id = f.folder_id
|
||||
WHERE uf.user_id = $1::uuid AND uf.item_type = 'file'"#;
|
||||
|
||||
if include_folders {
|
||||
cte_branches.push(folder_branch);
|
||||
}
|
||||
if include_files {
|
||||
cte_branches.push(file_branch);
|
||||
}
|
||||
|
||||
if cte_branches.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let union_sql = cte_branches.join("\n UNION ALL\n");
|
||||
let cte = format!("WITH resources AS ({union_sql}\n)");
|
||||
|
||||
// ── Cursor values ───────────────────────────────────────────────────
|
||||
let cur_str: Option<&str> = cursor.and_then(|c| c.sort_str.as_deref());
|
||||
let cur_int: Option<i64> = cursor.and_then(|c| c.sort_int);
|
||||
let cur_ts: Option<chrono::DateTime<chrono::Utc>> = cursor.and_then(|c| c.sort_ts);
|
||||
let cur_id: Option<Uuid> = cursor.map(|c| c.resource_id);
|
||||
|
||||
// ── Per-dimension keyset WHERE + ORDER BY ───────────────────────────
|
||||
// Binds: $1=user_id (in CTE), $2=cur_str, $3=cur_int, $4=cur_ts,
|
||||
// $5=cur_id, $6=limit (for "owner" sort: JOIN uses no extra binds)
|
||||
let (keyset, order_by_clause, need_user_join) = match (order_by, reverse) {
|
||||
// ── name ────────────────────────────────────────────────────────
|
||||
("name", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str > $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id > $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("name", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str < $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id < $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── type ────────────────────────────────────────────────────────
|
||||
("type", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order > $3)
|
||||
OR (type_order = $3 AND sort_str > $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND resource_id > $5::uuid)",
|
||||
"ORDER BY type_order ASC, sort_str ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("type", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order < $3)
|
||||
OR (type_order = $3 AND sort_str < $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND resource_id < $5::uuid)",
|
||||
"ORDER BY type_order DESC, sort_str DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── favorited_at ─────────────────────────────────────────────────
|
||||
("favorited_at", false) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (favorited_at < $4)
|
||||
OR (favorited_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY favorited_at DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
("favorited_at", true) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (favorited_at > $4)
|
||||
OR (favorited_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY favorited_at ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
// ── modified_at ──────────────────────────────────────────────────
|
||||
("modified_at", false) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at < $4)
|
||||
OR (modified_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY modified_at DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
("modified_at", true) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at > $4)
|
||||
OR (modified_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY modified_at ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
// ── size ─────────────────────────────────────────────────────────
|
||||
("size", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (size > $3)
|
||||
OR (size = $3 AND resource_id > $5::uuid)",
|
||||
"ORDER BY size ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("size", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (size < $3)
|
||||
OR (size = $3 AND resource_id < $5::uuid)",
|
||||
"ORDER BY size DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── owner ────────────────────────────────────────────────────────
|
||||
("owner", false) => (
|
||||
"WHERE ($2::text IS NULL)
|
||||
OR (LOWER(u.username) > $2)
|
||||
OR (LOWER(u.username) = $2 AND favorited_at < $4)
|
||||
OR (LOWER(u.username) = $2 AND favorited_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY LOWER(u.username) ASC, favorited_at DESC, resource_id DESC",
|
||||
true,
|
||||
),
|
||||
("owner", true) => (
|
||||
"WHERE ($2::text IS NULL)
|
||||
OR (LOWER(u.username) < $2)
|
||||
OR (LOWER(u.username) = $2 AND favorited_at > $4)
|
||||
OR (LOWER(u.username) = $2 AND favorited_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY LOWER(u.username) DESC, favorited_at ASC, resource_id ASC",
|
||||
true,
|
||||
),
|
||||
// ── default: same as name, ascending ─────────────────────────────
|
||||
(_, false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str > $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id > $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
(_, true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str < $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id < $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
};
|
||||
|
||||
let user_join = if need_user_join {
|
||||
"LEFT JOIN auth.users u ON u.id = r.owner_id"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
// For "owner" sort the JOIN makes LOWER(u.username) available; add it to SELECT
|
||||
// so the cursor can carry the correct sort key.
|
||||
let username_col = if need_user_join {
|
||||
",\n LOWER(u.username) AS username_lower"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"{cte}
|
||||
SELECT
|
||||
r.resource_type, r.resource_id, r.name, r.parent_id,
|
||||
r.mime_type, r.size, r.resource_created_at, r.modified_at,
|
||||
r.owner_id, r.is_owner, r.favorited_at, r.resource_path,
|
||||
r.sort_str, r.type_order, r.folder_first{username_col}
|
||||
FROM resources r
|
||||
{user_join}
|
||||
{keyset}
|
||||
{order_by_clause}
|
||||
LIMIT $6"
|
||||
);
|
||||
|
||||
let rows = sqlx::query(&sql)
|
||||
.bind(user_id) // $1 (in CTE + outer)
|
||||
.bind(cur_str) // $2
|
||||
.bind(cur_int) // $3
|
||||
.bind(cur_ts) // $4
|
||||
.bind(cur_id) // $5
|
||||
.bind(limit as i64) // $6
|
||||
.fetch_all(&*self.db_pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Database error listing favorite resources: {e}");
|
||||
DomainError::new(
|
||||
ErrorKind::InternalError,
|
||||
"Favorites",
|
||||
format!("Failed to list favorite resources: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let result = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let resource_type: String = row.get("resource_type");
|
||||
let sort_str_val: Option<String> = row.try_get("sort_str").ok();
|
||||
let type_order: i64 = row.try_get("type_order").unwrap_or(0);
|
||||
let folder_first: i32 = row.try_get("folder_first").unwrap_or(0);
|
||||
let size: i64 = row.get("size");
|
||||
|
||||
// Pre-compute the cursor sort fields based on order_by
|
||||
let (c_sort_str, c_sort_int, c_sort_ts) = match order_by {
|
||||
"name" => (sort_str_val, Some(folder_first as i64), None),
|
||||
"type" => (sort_str_val, Some(type_order), None),
|
||||
"size" => (None, Some(size), None),
|
||||
"favorited_at" => {
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("favorited_at").ok();
|
||||
(None, None, ts)
|
||||
}
|
||||
"modified_at" => {
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("modified_at").ok();
|
||||
(None, None, ts)
|
||||
}
|
||||
"owner" => {
|
||||
// For "owner" sort the JOIN added LOWER(u.username) AS username_lower.
|
||||
// The cursor's sort_str must carry the username (not the file name).
|
||||
let username: Option<String> = row.try_get("username_lower").ok();
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("favorited_at").ok();
|
||||
(username, None, ts)
|
||||
}
|
||||
_ => (sort_str_val, Some(folder_first as i64), None),
|
||||
};
|
||||
|
||||
FavoriteResourceRow {
|
||||
resource_type,
|
||||
resource_id: row.get("resource_id"),
|
||||
name: row.get("name"),
|
||||
parent_id: row.try_get("parent_id").ok(),
|
||||
mime_type: row.try_get("mime_type").ok(),
|
||||
size,
|
||||
resource_created_at: row.get("resource_created_at"),
|
||||
modified_at: row.get("modified_at"),
|
||||
owner_id: row.get("owner_id"),
|
||||
is_owner: row.try_get("is_owner").unwrap_or(false),
|
||||
favorited_at: row.get("favorited_at"),
|
||||
path: row.try_get("resource_path").ok(),
|
||||
sort_str: c_sort_str,
|
||||
sort_int: c_sort_int,
|
||||
sort_ts: c_sort_ts,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::folder_dto::{FolderResourceCursor, FolderResourceRow};
|
||||
use crate::common::errors::DomainError;
|
||||
use crate::domain::entities::folder::Folder;
|
||||
use crate::domain::repositories::folder_repository::FolderRepository;
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
use crate::domain::services::path_service::StoragePath;
|
||||
|
||||
/// Type alias for folder metadata rows from SQL queries.
|
||||
@@ -1060,4 +1062,238 @@ impl FolderDbRepository {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cursor-paginated combined listing of sub-folders and files inside
|
||||
/// `parent_id`, sorted by `order_by`.
|
||||
///
|
||||
/// **Authorization must be verified by the caller** before invoking this
|
||||
/// method — no ownership filter is applied here.
|
||||
///
|
||||
/// Fetches `limit` rows (caller should pass `desired_page_size + 1` to
|
||||
/// detect the existence of a next page). Returns raw [`FolderResourceRow`]
|
||||
/// values; the handler / service layer converts them to DTOs.
|
||||
pub async fn list_resources_paged(
|
||||
&self,
|
||||
parent_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&FolderResourceCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<FolderResourceRow>, DomainError> {
|
||||
let include_folders = kinds.is_none_or(|k| k.contains(&ResourceKind::Folder));
|
||||
let include_files = kinds.is_none_or(|k| k.contains(&ResourceKind::File));
|
||||
|
||||
if !include_folders && !include_files {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// ── CTE branches ────────────────────────────────────────────────────
|
||||
let folder_branch = r#"
|
||||
SELECT
|
||||
'folder'::text AS resource_type,
|
||||
f.id,
|
||||
f.name,
|
||||
f.parent_id AS folder_id,
|
||||
NULL::text AS mime_type,
|
||||
-1::bigint AS size,
|
||||
f.created_at,
|
||||
f.updated_at AS modified_at,
|
||||
f.user_id,
|
||||
LOWER(f.name) AS sort_str,
|
||||
0::bigint AS type_order,
|
||||
0::int AS folder_first
|
||||
FROM storage.folders f
|
||||
WHERE f.parent_id = $1::uuid AND NOT f.is_trashed
|
||||
"#;
|
||||
|
||||
let file_branch = r#"
|
||||
SELECT
|
||||
'file'::text AS resource_type,
|
||||
fm.id,
|
||||
fm.name,
|
||||
fm.folder_id,
|
||||
fm.mime_type,
|
||||
fm.size::bigint,
|
||||
fm.created_at,
|
||||
fm.updated_at AS modified_at,
|
||||
fm.user_id,
|
||||
LOWER(fm.name) AS sort_str,
|
||||
fm.category_order::bigint AS type_order,
|
||||
1::int AS folder_first
|
||||
FROM storage.files fm
|
||||
WHERE fm.folder_id = $1::uuid AND NOT fm.is_trashed
|
||||
"#;
|
||||
|
||||
let cte_inner = match (include_folders, include_files) {
|
||||
(true, true) => format!("{folder_branch} UNION ALL {file_branch}"),
|
||||
(true, false) => folder_branch.to_owned(),
|
||||
(false, true) => file_branch.to_owned(),
|
||||
(false, false) => unreachable!(),
|
||||
};
|
||||
|
||||
// ── Cursor binds ─────────────────────────────────────────────────────
|
||||
// $1 = parent_id $2 = cursor_str $3 = cursor_int
|
||||
// $4 = cursor_ts $5 = cursor_id $6 = limit
|
||||
let cursor_str = cursor.and_then(|c| c.sort_str.clone());
|
||||
let cursor_int = cursor.and_then(|c| c.sort_int);
|
||||
let cursor_ts = cursor.and_then(|c| c.sort_ts);
|
||||
let cursor_id = cursor.map(|c| c.resource_id);
|
||||
|
||||
// ── Sort-specific WHERE + ORDER BY ───────────────────────────────────
|
||||
// Each arm produces two variants based on `reverse`.
|
||||
// For "name": folder_first stays ASC in both directions (folders always
|
||||
// precede files); only the alpha order within each group flips.
|
||||
let (where_clause, order_clause) = match order_by {
|
||||
"type" => {
|
||||
if reverse {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order < $3)
|
||||
OR (type_order = $3 AND sort_str < $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND id < $5::uuid)"#,
|
||||
"ORDER BY type_order DESC, sort_str DESC, id DESC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order > $3)
|
||||
OR (type_order = $3 AND sort_str > $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND id > $5::uuid)"#,
|
||||
"ORDER BY type_order ASC, sort_str ASC, id ASC",
|
||||
)
|
||||
}
|
||||
}
|
||||
"modified_at" => {
|
||||
if reverse {
|
||||
(
|
||||
r#"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at > $4)
|
||||
OR (modified_at = $4 AND id > $5::uuid)"#,
|
||||
"ORDER BY modified_at ASC, id ASC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at < $4)
|
||||
OR (modified_at = $4 AND id < $5::uuid)"#,
|
||||
"ORDER BY modified_at DESC, id DESC",
|
||||
)
|
||||
}
|
||||
}
|
||||
"created_at" => {
|
||||
if reverse {
|
||||
(
|
||||
r#"WHERE ($4::timestamptz IS NULL)
|
||||
OR (created_at > $4)
|
||||
OR (created_at = $4 AND id > $5::uuid)"#,
|
||||
"ORDER BY created_at ASC, id ASC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"WHERE ($4::timestamptz IS NULL)
|
||||
OR (created_at < $4)
|
||||
OR (created_at = $4 AND id < $5::uuid)"#,
|
||||
"ORDER BY created_at DESC, id DESC",
|
||||
)
|
||||
}
|
||||
}
|
||||
"size" => {
|
||||
if reverse {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (size < $3)
|
||||
OR (size = $3 AND id < $5::uuid)"#,
|
||||
"ORDER BY size DESC, id DESC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (size > $3)
|
||||
OR (size = $3 AND id > $5::uuid)"#,
|
||||
"ORDER BY size ASC, id ASC",
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// "name" (default): folder_first stays ASC so folders always precede
|
||||
// files; only the alpha order within each group flips when reversed.
|
||||
if reverse {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str < $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND id < $5::uuid)"#,
|
||||
"ORDER BY folder_first ASC, sort_str DESC, id DESC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str > $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND id > $5::uuid)"#,
|
||||
"ORDER BY folder_first ASC, sort_str ASC, id ASC",
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"WITH resources AS ({cte_inner}) \
|
||||
SELECT resource_type, id, name, folder_id, mime_type, size, \
|
||||
created_at, modified_at, user_id, sort_str, type_order, folder_first \
|
||||
FROM resources \
|
||||
{where_clause} \
|
||||
{order_clause} \
|
||||
LIMIT $6"
|
||||
);
|
||||
|
||||
// Row: (resource_type, id, name, folder_id, mime_type, size,
|
||||
// created_at, modified_at, user_id, sort_str, type_order, folder_first)
|
||||
type Row = (
|
||||
String,
|
||||
Uuid,
|
||||
String,
|
||||
Option<Uuid>,
|
||||
Option<String>,
|
||||
i64,
|
||||
chrono::DateTime<chrono::Utc>,
|
||||
chrono::DateTime<chrono::Utc>,
|
||||
Uuid,
|
||||
String,
|
||||
i64,
|
||||
i32,
|
||||
);
|
||||
|
||||
let rows = sqlx::query_as::<_, Row>(&sql)
|
||||
.bind(parent_id)
|
||||
.bind(cursor_str)
|
||||
.bind(cursor_int)
|
||||
.bind(cursor_ts)
|
||||
.bind(cursor_id)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(self.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
DomainError::internal_error("FolderDb", format!("list_resources_paged: {e}"))
|
||||
})?;
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| FolderResourceRow {
|
||||
resource_type: r.0,
|
||||
id: r.1,
|
||||
name: r.2,
|
||||
parent_id: r.3,
|
||||
mime_type: r.4,
|
||||
size: r.5,
|
||||
created_at: r.6,
|
||||
modified_at: r.7,
|
||||
owner_id: r.8,
|
||||
sort_str: r.9,
|
||||
type_order: r.10,
|
||||
folder_first: r.11,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@ use std::sync::Arc;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::recent_dto::RecentItemDto;
|
||||
use crate::application::dtos::recent_dto::{RecentCursor, RecentItemDto, RecentResourceRow};
|
||||
use crate::application::ports::recent_ports::RecentItemsRepositoryPort;
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// PostgreSQL implementation of the recent items persistence port.
|
||||
pub struct RecentItemsPgRepository {
|
||||
@@ -188,4 +189,310 @@ impl RecentItemsRepositoryPort for RecentItemsPgRepository {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&RecentCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<RecentResourceRow>> {
|
||||
let include_folders =
|
||||
kinds.is_none_or(|k| k.iter().any(|r| matches!(r, ResourceKind::Folder)));
|
||||
let include_files = kinds.is_none_or(|k| k.iter().any(|r| matches!(r, ResourceKind::File)));
|
||||
|
||||
// ── Build the UNION ALL CTE ─────────────────────────────────────────
|
||||
let mut cte_branches: Vec<&str> = Vec::new();
|
||||
|
||||
let folder_branch = r#"
|
||||
SELECT
|
||||
'folder'::text AS resource_type,
|
||||
fld.id AS resource_id,
|
||||
fld.name,
|
||||
fld.parent_id,
|
||||
NULL::text AS mime_type,
|
||||
-1::bigint AS size,
|
||||
fld.created_at AS resource_created_at,
|
||||
fld.updated_at AS modified_at,
|
||||
fld.user_id AS owner_id,
|
||||
(fld.user_id = $1::uuid) AS is_owner,
|
||||
ur.accessed_at AS accessed_at,
|
||||
fld.path::text AS resource_path,
|
||||
LOWER(fld.name) AS sort_str,
|
||||
0::bigint AS type_order,
|
||||
0::int AS folder_first
|
||||
FROM auth.user_recent_files ur
|
||||
INNER JOIN storage.folders fld
|
||||
ON fld.id = ur.item_id::UUID AND NOT fld.is_trashed
|
||||
WHERE ur.user_id = $1::uuid AND ur.item_type = 'folder'"#;
|
||||
|
||||
let file_branch = r#"
|
||||
SELECT
|
||||
'file'::text AS resource_type,
|
||||
f.id AS resource_id,
|
||||
f.name,
|
||||
f.folder_id AS parent_id,
|
||||
f.mime_type,
|
||||
f.size::bigint,
|
||||
f.created_at AS resource_created_at,
|
||||
f.updated_at AS modified_at,
|
||||
f.user_id AS owner_id,
|
||||
(f.user_id = $1::uuid) AS is_owner,
|
||||
ur.accessed_at AS accessed_at,
|
||||
COALESCE(pfld.path::text || '/' || f.name, f.name) AS resource_path,
|
||||
LOWER(f.name) AS sort_str,
|
||||
f.category_order::bigint AS type_order,
|
||||
1::int AS folder_first
|
||||
FROM auth.user_recent_files ur
|
||||
INNER JOIN storage.files f
|
||||
ON f.id = ur.item_id::UUID AND NOT f.is_trashed
|
||||
LEFT JOIN storage.folders pfld
|
||||
ON pfld.id = f.folder_id
|
||||
WHERE ur.user_id = $1::uuid AND ur.item_type = 'file'"#;
|
||||
|
||||
if include_folders {
|
||||
cte_branches.push(folder_branch);
|
||||
}
|
||||
if include_files {
|
||||
cte_branches.push(file_branch);
|
||||
}
|
||||
|
||||
if cte_branches.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let union_sql = cte_branches.join("\n UNION ALL\n");
|
||||
let cte = format!("WITH resources AS ({union_sql}\n)");
|
||||
|
||||
// ── Cursor values ───────────────────────────────────────────────────
|
||||
let cur_str: Option<&str> = cursor.and_then(|c| c.sort_str.as_deref());
|
||||
let cur_int: Option<i64> = cursor.and_then(|c| c.sort_int);
|
||||
let cur_ts: Option<chrono::DateTime<chrono::Utc>> = cursor.and_then(|c| c.sort_ts);
|
||||
let cur_id: Option<Uuid> = cursor.map(|c| c.resource_id);
|
||||
|
||||
// ── Per-dimension keyset WHERE + ORDER BY ───────────────────────────
|
||||
// Binds: $1=user_id (in CTE), $2=cur_str, $3=cur_int, $4=cur_ts,
|
||||
// $5=cur_id, $6=limit (for "owner" sort: JOIN uses no extra binds)
|
||||
let (keyset, order_by_clause, need_user_join) = match (order_by, reverse) {
|
||||
// ── name ────────────────────────────────────────────────────────
|
||||
("name", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str > $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id > $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("name", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (folder_first::bigint > $3)
|
||||
OR (folder_first::bigint = $3 AND sort_str < $2)
|
||||
OR (folder_first::bigint = $3 AND sort_str = $2 AND resource_id < $5::uuid)",
|
||||
"ORDER BY folder_first ASC, sort_str DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── type ────────────────────────────────────────────────────────
|
||||
("type", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order > $3)
|
||||
OR (type_order = $3 AND sort_str > $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND resource_id > $5::uuid)",
|
||||
"ORDER BY type_order ASC, sort_str ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("type", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (type_order < $3)
|
||||
OR (type_order = $3 AND sort_str < $2)
|
||||
OR (type_order = $3 AND sort_str = $2 AND resource_id < $5::uuid)",
|
||||
"ORDER BY type_order DESC, sort_str DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── accessed_at ──────────────────────────────────────────────────
|
||||
("accessed_at", false) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (accessed_at < $4)
|
||||
OR (accessed_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY accessed_at DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
("accessed_at", true) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (accessed_at > $4)
|
||||
OR (accessed_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY accessed_at ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
// ── modified_at ──────────────────────────────────────────────────
|
||||
("modified_at", false) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at < $4)
|
||||
OR (modified_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY modified_at DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
("modified_at", true) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (modified_at > $4)
|
||||
OR (modified_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY modified_at ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
// ── size ─────────────────────────────────────────────────────────
|
||||
("size", false) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (size > $3)
|
||||
OR (size = $3 AND resource_id > $5::uuid)",
|
||||
"ORDER BY size ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
("size", true) => (
|
||||
"WHERE ($3::bigint IS NULL)
|
||||
OR (size < $3)
|
||||
OR (size = $3 AND resource_id < $5::uuid)",
|
||||
"ORDER BY size DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
// ── owner ────────────────────────────────────────────────────────
|
||||
("owner", false) => (
|
||||
"WHERE ($2::text IS NULL)
|
||||
OR (LOWER(u.username) > $2)
|
||||
OR (LOWER(u.username) = $2 AND accessed_at < $4)
|
||||
OR (LOWER(u.username) = $2 AND accessed_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY LOWER(u.username) ASC, accessed_at DESC, resource_id DESC",
|
||||
true,
|
||||
),
|
||||
("owner", true) => (
|
||||
"WHERE ($2::text IS NULL)
|
||||
OR (LOWER(u.username) < $2)
|
||||
OR (LOWER(u.username) = $2 AND accessed_at > $4)
|
||||
OR (LOWER(u.username) = $2 AND accessed_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY LOWER(u.username) DESC, accessed_at ASC, resource_id ASC",
|
||||
true,
|
||||
),
|
||||
// ── default: accessed_at DESC ─────────────────────────────────────
|
||||
(_, false) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (accessed_at < $4)
|
||||
OR (accessed_at = $4 AND resource_id < $5::uuid)",
|
||||
"ORDER BY accessed_at DESC, resource_id DESC",
|
||||
false,
|
||||
),
|
||||
(_, true) => (
|
||||
"WHERE ($4::timestamptz IS NULL)
|
||||
OR (accessed_at > $4)
|
||||
OR (accessed_at = $4 AND resource_id > $5::uuid)",
|
||||
"ORDER BY accessed_at ASC, resource_id ASC",
|
||||
false,
|
||||
),
|
||||
};
|
||||
|
||||
let user_join = if need_user_join {
|
||||
"LEFT JOIN auth.users u ON u.id = r.owner_id"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
// For "owner" sort the JOIN makes LOWER(u.username) available; add it to SELECT
|
||||
// so the cursor can carry the correct sort key.
|
||||
let username_col = if need_user_join {
|
||||
",\n LOWER(u.username) AS username_lower"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"{cte}
|
||||
SELECT
|
||||
r.resource_type, r.resource_id, r.name, r.parent_id,
|
||||
r.mime_type, r.size, r.resource_created_at, r.modified_at,
|
||||
r.owner_id, r.is_owner, r.accessed_at, r.resource_path,
|
||||
r.sort_str, r.type_order, r.folder_first{username_col}
|
||||
FROM resources r
|
||||
{user_join}
|
||||
{keyset}
|
||||
{order_by_clause}
|
||||
LIMIT $6"
|
||||
);
|
||||
|
||||
let rows = sqlx::query(&sql)
|
||||
.bind(user_id) // $1 (in CTE + outer)
|
||||
.bind(cur_str) // $2
|
||||
.bind(cur_int) // $3
|
||||
.bind(cur_ts) // $4
|
||||
.bind(cur_id) // $5
|
||||
.bind(limit as i64) // $6
|
||||
.fetch_all(&*self.db_pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Database error listing recent resources: {e}");
|
||||
DomainError::new(
|
||||
ErrorKind::InternalError,
|
||||
"RecentItems",
|
||||
format!("Failed to list recent resources: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let result = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let resource_type: String = row.get("resource_type");
|
||||
let sort_str_val: Option<String> = row.try_get("sort_str").ok();
|
||||
let type_order: i64 = row.try_get("type_order").unwrap_or(0);
|
||||
let folder_first: i32 = row.try_get("folder_first").unwrap_or(0);
|
||||
let size: i64 = row.get("size");
|
||||
|
||||
// Pre-compute the cursor sort fields based on order_by
|
||||
let (c_sort_str, c_sort_int, c_sort_ts) = match order_by {
|
||||
"name" => (sort_str_val, Some(folder_first as i64), None),
|
||||
"type" => (sort_str_val, Some(type_order), None),
|
||||
"size" => (None, Some(size), None),
|
||||
"accessed_at" => {
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("accessed_at").ok();
|
||||
(None, None, ts)
|
||||
}
|
||||
"modified_at" => {
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("modified_at").ok();
|
||||
(None, None, ts)
|
||||
}
|
||||
"owner" => {
|
||||
// For "owner" sort the JOIN added LOWER(u.username) AS username_lower.
|
||||
// The cursor's sort_str must carry the username (not the file name).
|
||||
let username: Option<String> = row.try_get("username_lower").ok();
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("accessed_at").ok();
|
||||
(username, None, ts)
|
||||
}
|
||||
_ => {
|
||||
let ts: Option<chrono::DateTime<chrono::Utc>> =
|
||||
row.try_get("accessed_at").ok();
|
||||
(None, None, ts)
|
||||
}
|
||||
};
|
||||
|
||||
RecentResourceRow {
|
||||
resource_type,
|
||||
resource_id: row.get("resource_id"),
|
||||
name: row.get("name"),
|
||||
parent_id: row.try_get("parent_id").ok(),
|
||||
mime_type: row.try_get("mime_type").ok(),
|
||||
size,
|
||||
resource_created_at: row.get("resource_created_at"),
|
||||
modified_at: row.get("modified_at"),
|
||||
owner_id: row.get("owner_id"),
|
||||
is_owner: row.try_get("is_owner").unwrap_or(false),
|
||||
accessed_at: row.get("accessed_at"),
|
||||
path: row.try_get("resource_path").ok(),
|
||||
sort_str: c_sort_str,
|
||||
sort_int: c_sort_int,
|
||||
sort_ts: c_sort_ts,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,6 +300,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
limit: u32,
|
||||
cursor: Option<GrantCursor>,
|
||||
sort_by: &str,
|
||||
reverse: bool,
|
||||
) -> Result<(Vec<IncomingGrantSummary>, Option<GrantCursor>), DomainError> {
|
||||
// ── Common setup ──────────────────────────────────────────────────────
|
||||
let kind_strs: Option<Vec<&str>> = if kinds.is_empty() {
|
||||
@@ -358,6 +359,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
// ── Build sort-specific SQL fragments ─────────────────────────────────
|
||||
// "name" and "type" share the same LEFT JOINs; only sort_int_expr,
|
||||
// the cursor WHERE condition, and ORDER BY differ.
|
||||
// Each branch emits two variants selected by `reverse`.
|
||||
let sql = match sort_by {
|
||||
"name" | "type" => {
|
||||
let sort_int_expr = if sort_by == "type" {
|
||||
@@ -365,20 +367,39 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
} else {
|
||||
"NULL::bigint"
|
||||
};
|
||||
let where_clause = if sort_by == "type" {
|
||||
r#"( $5::integer IS NULL
|
||||
OR sort_int > $5
|
||||
OR (sort_int = $5 AND LOWER(sort_str) > $4)
|
||||
OR (sort_int = $5 AND LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#
|
||||
// Normal vs reversed keyset + ORDER BY.
|
||||
let (where_clause, order_clause) = if sort_by == "type" {
|
||||
if reverse {
|
||||
(
|
||||
r#"( $5::integer IS NULL
|
||||
OR sort_int < $5
|
||||
OR (sort_int = $5 AND LOWER(sort_str) < $4)
|
||||
OR (sort_int = $5 AND LOWER(sort_str) = $4 AND resource_id < $7::uuid))"#,
|
||||
"sort_int DESC, LOWER(sort_str) DESC, resource_id DESC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"( $5::integer IS NULL
|
||||
OR sort_int > $5
|
||||
OR (sort_int = $5 AND LOWER(sort_str) > $4)
|
||||
OR (sort_int = $5 AND LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#,
|
||||
"sort_int ASC, LOWER(sort_str) ASC, resource_id ASC",
|
||||
)
|
||||
}
|
||||
} else if reverse {
|
||||
(
|
||||
r#"( $4::text IS NULL
|
||||
OR LOWER(sort_str) < $4
|
||||
OR (LOWER(sort_str) = $4 AND resource_id < $7::uuid))"#,
|
||||
"LOWER(sort_str) DESC, resource_id DESC",
|
||||
)
|
||||
} else {
|
||||
r#"( $4::text IS NULL
|
||||
OR LOWER(sort_str) > $4
|
||||
OR (LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#
|
||||
};
|
||||
let order_clause = if sort_by == "type" {
|
||||
"sort_int ASC, LOWER(sort_str) ASC, resource_id ASC"
|
||||
} else {
|
||||
"LOWER(sort_str) ASC, resource_id ASC"
|
||||
(
|
||||
r#"( $4::text IS NULL
|
||||
OR LOWER(sort_str) > $4
|
||||
OR (LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#,
|
||||
"LOWER(sort_str) ASC, resource_id ASC",
|
||||
)
|
||||
};
|
||||
format!(
|
||||
r#"WITH {AGG},
|
||||
@@ -400,64 +421,112 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
LIMIT $8"#
|
||||
)
|
||||
}
|
||||
"granted_by" => format!(
|
||||
"granted_by" => {
|
||||
// Joins auth.users to sort alphabetically by username.
|
||||
// Cursor encodes (owner_name=$4, granted_at=$6, resource_id=$7).
|
||||
r#"WITH {AGG},
|
||||
owner_named AS (
|
||||
SELECT agg.*,
|
||||
LOWER(u.username) AS sort_str,
|
||||
NULL::bigint AS sort_int
|
||||
FROM agg
|
||||
LEFT JOIN auth.users u ON u.id = agg.granted_by
|
||||
let (where_clause, order_clause) = if reverse {
|
||||
(
|
||||
r#"( $4::text IS NULL
|
||||
OR sort_str < $4
|
||||
OR (sort_str = $4 AND (
|
||||
$6::timestamptz IS NULL
|
||||
OR granted_at > $6
|
||||
OR (granted_at = $6 AND resource_id > $7::uuid))))"#,
|
||||
"sort_str DESC, granted_at ASC, resource_id ASC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"( $4::text IS NULL
|
||||
OR sort_str > $4
|
||||
OR (sort_str = $4 AND (
|
||||
$6::timestamptz IS NULL
|
||||
OR granted_at < $6
|
||||
OR (granted_at = $6 AND resource_id < $7::uuid))))"#,
|
||||
"sort_str ASC, granted_at DESC, resource_id DESC",
|
||||
)
|
||||
};
|
||||
format!(
|
||||
r#"WITH {AGG},
|
||||
owner_named AS (
|
||||
SELECT agg.*,
|
||||
LOWER(u.username) AS sort_str,
|
||||
NULL::bigint AS sort_int
|
||||
FROM agg
|
||||
LEFT JOIN auth.users u ON u.id = agg.granted_by
|
||||
)
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
|
||||
FROM owner_named
|
||||
WHERE {where_clause}
|
||||
ORDER BY {order_clause}
|
||||
LIMIT $8"#
|
||||
)
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
|
||||
FROM owner_named
|
||||
WHERE ( $4::text IS NULL
|
||||
OR sort_str > $4
|
||||
OR (sort_str = $4 AND (
|
||||
$6::timestamptz IS NULL
|
||||
OR granted_at < $6
|
||||
OR (granted_at = $6 AND resource_id < $7::uuid))))
|
||||
ORDER BY sort_str ASC, granted_at DESC, resource_id DESC
|
||||
LIMIT $8"#
|
||||
),
|
||||
"size" => format!(
|
||||
// Folders have no size — they sort first with a sentinel of -1.
|
||||
// Files sort by size ASC; resource_id breaks ties.
|
||||
}
|
||||
"size" => {
|
||||
// Folders have no size — sentinel -1 (sorts first ASC, last DESC).
|
||||
// Cursor encodes (sort_int=$5, resource_id=$7); $4/$6 unused.
|
||||
r#"WITH {AGG},
|
||||
sized AS (
|
||||
SELECT agg.*,
|
||||
NULL::text AS sort_str,
|
||||
CASE WHEN agg.resource_type = 'folder' THEN -1
|
||||
ELSE fi.size
|
||||
END AS sort_int
|
||||
FROM agg
|
||||
LEFT JOIN storage.files fi ON fi.id = agg.resource_id AND agg.resource_type = 'file'
|
||||
let (where_clause, order_clause) = if reverse {
|
||||
(
|
||||
r#"( $5::bigint IS NULL
|
||||
OR sort_int < $5
|
||||
OR (sort_int = $5 AND resource_id < $7::uuid))"#,
|
||||
"sort_int DESC, resource_id DESC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"( $5::bigint IS NULL
|
||||
OR sort_int > $5
|
||||
OR (sort_int = $5 AND resource_id > $7::uuid))"#,
|
||||
"sort_int ASC, resource_id ASC",
|
||||
)
|
||||
};
|
||||
format!(
|
||||
r#"WITH {AGG},
|
||||
sized AS (
|
||||
SELECT agg.*,
|
||||
NULL::text AS sort_str,
|
||||
CASE WHEN agg.resource_type = 'folder' THEN -1
|
||||
ELSE fi.size
|
||||
END AS sort_int
|
||||
FROM agg
|
||||
LEFT JOIN storage.files fi ON fi.id = agg.resource_id AND agg.resource_type = 'file'
|
||||
)
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
|
||||
FROM sized
|
||||
WHERE {where_clause}
|
||||
ORDER BY {order_clause}
|
||||
LIMIT $8"#
|
||||
)
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
|
||||
FROM sized
|
||||
WHERE ( $5::bigint IS NULL
|
||||
OR sort_int > $5
|
||||
OR (sort_int = $5 AND resource_id > $7::uuid))
|
||||
ORDER BY sort_int ASC, resource_id ASC
|
||||
LIMIT $8"#
|
||||
),
|
||||
_ => format!(
|
||||
// Default: sort by grant date DESC (newest first).
|
||||
}
|
||||
_ => {
|
||||
// Default: sort by grant date.
|
||||
// Normal = DESC (newest first); reversed = ASC (oldest first).
|
||||
// Cursor encodes (granted_at=$6, resource_id=$7); $4/$5 unused.
|
||||
r#"WITH {AGG}
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by,
|
||||
NULL::text AS sort_str,
|
||||
NULL::bigint AS sort_int
|
||||
FROM agg
|
||||
WHERE ( $6::timestamptz IS NULL
|
||||
OR granted_at < $6
|
||||
OR (granted_at = $6 AND resource_id < $7::uuid))
|
||||
ORDER BY granted_at DESC, resource_id DESC
|
||||
LIMIT $8"#
|
||||
),
|
||||
let (where_clause, order_clause) = if reverse {
|
||||
(
|
||||
r#"( $6::timestamptz IS NULL
|
||||
OR granted_at > $6
|
||||
OR (granted_at = $6 AND resource_id > $7::uuid))"#,
|
||||
"granted_at ASC, resource_id ASC",
|
||||
)
|
||||
} else {
|
||||
(
|
||||
r#"( $6::timestamptz IS NULL
|
||||
OR granted_at < $6
|
||||
OR (granted_at = $6 AND resource_id < $7::uuid))"#,
|
||||
"granted_at DESC, resource_id DESC",
|
||||
)
|
||||
};
|
||||
format!(
|
||||
r#"WITH {AGG}
|
||||
SELECT resource_type, resource_id, permissions, granted_at, granted_by,
|
||||
NULL::text AS sort_str,
|
||||
NULL::bigint AS sort_int
|
||||
FROM agg
|
||||
WHERE {where_clause}
|
||||
ORDER BY {order_clause}
|
||||
LIMIT $8"#
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
// ── Execute — uniform 8 binds for every sort mode ─────────────────────
|
||||
@@ -493,6 +562,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
resource_id: r.1,
|
||||
resource_name: sort_str_lc,
|
||||
sort_int: None,
|
||||
reverse,
|
||||
},
|
||||
"type" => GrantCursor {
|
||||
sort_by: "type".to_owned(),
|
||||
@@ -500,6 +570,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
resource_id: r.1,
|
||||
resource_name: sort_str_lc,
|
||||
sort_int: r.6,
|
||||
reverse,
|
||||
},
|
||||
"granted_by" => GrantCursor {
|
||||
sort_by: "granted_by".to_owned(),
|
||||
@@ -507,6 +578,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
resource_id: r.1,
|
||||
resource_name: r.5.clone(), // already lowercased by SQL
|
||||
sort_int: None,
|
||||
reverse,
|
||||
},
|
||||
"size" => GrantCursor {
|
||||
sort_by: "size".to_owned(),
|
||||
@@ -514,6 +586,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
resource_id: r.1,
|
||||
resource_name: None,
|
||||
sort_int: r.6,
|
||||
reverse,
|
||||
},
|
||||
_ => GrantCursor {
|
||||
sort_by: "granted_at".to_owned(),
|
||||
@@ -521,6 +594,7 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
resource_id: r.1,
|
||||
resource_name: None,
|
||||
sort_int: None,
|
||||
reverse,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
extract::{Path, Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
};
|
||||
@@ -9,8 +9,18 @@ use std::sync::Arc;
|
||||
use tracing::{error, info};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use crate::application::dtos::favorites_dto::{
|
||||
FavoritesResourceItemDto, FavoritesResourcesDto, FavoritesResourcesQuery,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::FolderDto;
|
||||
use crate::application::dtos::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::application::ports::favorites_ports::FavoritesUseCase;
|
||||
use crate::application::services::favorites_service::FavoritesService;
|
||||
use crate::interfaces::errors::AppError;
|
||||
use crate::interfaces::middleware::auth::AuthUser;
|
||||
|
||||
/// Single item in a batch-add-favorites request.
|
||||
@@ -27,11 +37,16 @@ pub struct BatchFavoritesRequest {
|
||||
}
|
||||
|
||||
/// Handler for favorite-related API endpoints
|
||||
///
|
||||
/// # Deprecated
|
||||
/// Use `GET /api/favorites/resources` instead. This endpoint is kept for
|
||||
/// backwards compatibility but will be removed in a future release.
|
||||
#[deprecated = "Use GET /api/favorites/resources instead"]
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/favorites",
|
||||
responses(
|
||||
(status = 200, description = "List of favorites", body = Vec<crate::application::dtos::favorites_dto::FavoriteItemDto>)
|
||||
(status = 200, description = "List of favorites (deprecated — use /api/favorites/resources)", body = Vec<crate::application::dtos::favorites_dto::FavoriteItemDto>)
|
||||
),
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "favorites"
|
||||
@@ -178,6 +193,125 @@ pub async fn remove_favorite(
|
||||
}
|
||||
}
|
||||
|
||||
/// Cursor-paginated list of a user's favorited resources.
|
||||
///
|
||||
/// Supports sorting by `name`, `type`, `favorited_at`, `modified_at`, `size`, or `owner`.
|
||||
/// Items that have been deleted/trashed are silently excluded.
|
||||
/// `path` is cleared when the resource is not owned by the requesting user.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/favorites/resources",
|
||||
params(FavoritesResourcesQuery),
|
||||
responses(
|
||||
(status = 200, description = "Paginated list of favorited resources",
|
||||
body = crate::application::dtos::favorites_dto::FavoritesResourcesDto),
|
||||
(status = 400, description = "Invalid cursor or query parameters"),
|
||||
),
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "favorites"
|
||||
)]
|
||||
pub async fn list_favorites_resources(
|
||||
State(favorites_service): State<Arc<FavoritesService>>,
|
||||
auth_user: AuthUser,
|
||||
Query(q): Query<FavoritesResourcesQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let user_id = auth_user.id;
|
||||
|
||||
let order_by = q.order_by.as_deref().unwrap_or("name").to_owned();
|
||||
|
||||
// If a cursor exists, validate that it matches the requested sort/direction.
|
||||
let cursor = q
|
||||
.decode_cursor()
|
||||
.filter(|c| c.order_by == order_by && c.reverse == q.reverse);
|
||||
|
||||
let kinds = q.resource_kinds();
|
||||
|
||||
match favorites_service
|
||||
.list_resources_paged(
|
||||
user_id,
|
||||
q.limit_clamped(),
|
||||
cursor,
|
||||
&order_by,
|
||||
kinds.as_deref(),
|
||||
q.reverse,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((rows, next_cursor)) => {
|
||||
let items: Vec<FavoritesResourceItemDto> = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
// Path is only shown to the owner; non-owners see ""
|
||||
// to avoid leaking another user's folder hierarchy.
|
||||
let path = if row.is_owner {
|
||||
row.path.clone().unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
if row.resource_type == "folder" {
|
||||
let dto = FolderDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path,
|
||||
parent_id: row.parent_id.map(|u| u.to_string()),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
created_at: row.resource_created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
is_root: false,
|
||||
icon_class: std::sync::Arc::from("fas fa-folder"),
|
||||
icon_special_class: std::sync::Arc::from("folder-icon"),
|
||||
category: std::sync::Arc::from("Folder"),
|
||||
};
|
||||
FavoritesResourceItemDto {
|
||||
resource_type: ResourceTypeDto::Folder,
|
||||
favorited_at: row.favorited_at,
|
||||
resource: ResourceContentDto::Folder(dto),
|
||||
}
|
||||
} else {
|
||||
let mime = row
|
||||
.mime_type
|
||||
.as_deref()
|
||||
.unwrap_or("application/octet-stream");
|
||||
let size_bytes = row.size.max(0) as u64;
|
||||
let dto = FileDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path,
|
||||
size: size_bytes,
|
||||
mime_type: std::sync::Arc::from(mime),
|
||||
folder_id: row.parent_id.map(|u| u.to_string()),
|
||||
created_at: row.resource_created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
icon_class: std::sync::Arc::from(icon_class_for(&row.name, mime)),
|
||||
icon_special_class: std::sync::Arc::from(icon_special_class_for(
|
||||
&row.name, mime,
|
||||
)),
|
||||
category: std::sync::Arc::from(category_for(&row.name, mime)),
|
||||
size_formatted: format_file_size(size_bytes),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
sort_date: None,
|
||||
etag: String::new(),
|
||||
};
|
||||
FavoritesResourceItemDto {
|
||||
resource_type: ResourceTypeDto::File,
|
||||
favorited_at: row.favorited_at,
|
||||
resource: ResourceContentDto::File(dto),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(FavoritesResourcesDto::with_cursor(items, next_cursor)),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => AppError::from(e).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add multiple items to favourites in a single transaction.
|
||||
/// POST /api/favorites/batch
|
||||
#[utoipa::path(
|
||||
|
||||
@@ -10,10 +10,16 @@ use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::{
|
||||
CreateFolderDto, FolderDto, MoveFolderDto, RenameFolderDto,
|
||||
CreateFolderDto, FolderDto, FolderResourceItemDto, FolderResourcesDto, FolderResourcesQuery,
|
||||
ListResourcesOptions, MoveFolderDto, RenameFolderDto,
|
||||
};
|
||||
use crate::application::dtos::folder_listing_dto::FolderListingDto;
|
||||
use crate::application::dtos::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::application::dtos::pagination::PaginationRequestDto;
|
||||
use crate::application::ports::file_ports::FileRetrievalUseCase;
|
||||
use crate::application::ports::folder_ports::FolderUseCase;
|
||||
@@ -466,6 +472,7 @@ pub async fn list_root_folders(
|
||||
FolderHandler::list_root_folders_impl(state, auth_user).await
|
||||
}
|
||||
|
||||
#[deprecated = "Use /api/folders/{id}/resources instead"]
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/folders/{id}/contents",
|
||||
@@ -477,6 +484,7 @@ pub async fn list_root_folders(
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "folders"
|
||||
)]
|
||||
#[allow(deprecated)]
|
||||
pub async fn list_folder_contents(
|
||||
state: State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
@@ -503,6 +511,7 @@ pub async fn list_root_folders_paginated(
|
||||
FolderHandler::list_root_folders_paginated_impl(state, auth_user, pagination).await
|
||||
}
|
||||
|
||||
#[deprecated = "Use /api/folders/{id}/resources instead"]
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/folders/{id}/contents/paginated",
|
||||
@@ -517,6 +526,7 @@ pub async fn list_root_folders_paginated(
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "folders"
|
||||
)]
|
||||
#[allow(deprecated)]
|
||||
pub async fn list_folder_contents_paginated(
|
||||
state: State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
@@ -526,6 +536,7 @@ pub async fn list_folder_contents_paginated(
|
||||
FolderHandler::list_folder_contents_paginated_impl(state, auth_user, path, pagination).await
|
||||
}
|
||||
|
||||
#[deprecated = "Use /api/folders/{id}/resources instead"]
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/folders/{id}/listing",
|
||||
@@ -538,6 +549,7 @@ pub async fn list_folder_contents_paginated(
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "folders"
|
||||
)]
|
||||
#[allow(deprecated)]
|
||||
pub async fn list_folder_listing(
|
||||
state: State<Arc<GlobalAppState>>,
|
||||
auth_user: AuthUser,
|
||||
@@ -628,3 +640,105 @@ pub async fn download_folder_zip(
|
||||
) -> impl IntoResponse {
|
||||
FolderHandler::download_folder_zip_impl(state, auth_user, path, query).await
|
||||
}
|
||||
|
||||
// ── GET /api/folders/{id}/resources ─────────────────────────────────────────
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/folders/{id}/resources",
|
||||
params(
|
||||
("id" = String, Path, description = "Folder ID"),
|
||||
FolderResourcesQuery,
|
||||
),
|
||||
responses(
|
||||
(status = 200,
|
||||
description = "Cursor-paginated files and folders inside the requested folder. \
|
||||
Items arrive in `order_by` order (folders first when order_by=name). \
|
||||
`next_cursor` is absent on the last page.",
|
||||
body = FolderResourcesDto),
|
||||
(status = 404, description = "Folder not found or access denied"),
|
||||
),
|
||||
tag = "folders"
|
||||
)]
|
||||
pub async fn list_folder_resources(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
Path(id): Path<String>,
|
||||
Query(q): Query<FolderResourcesQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let order_by = q.order_by.clone().unwrap_or_else(|| "name".to_owned());
|
||||
let kinds = q.resource_kinds();
|
||||
let opts = ListResourcesOptions {
|
||||
limit: q.limit_clamped(),
|
||||
cursor: q.decode_cursor(),
|
||||
order_by: &order_by,
|
||||
kinds: kinds.as_deref(),
|
||||
reverse: q.reverse,
|
||||
};
|
||||
|
||||
match service
|
||||
.list_resources_paged_with_perms(&id, auth_user.id, opts)
|
||||
.await
|
||||
{
|
||||
Ok((rows, next_cursor)) => {
|
||||
let items: Vec<FolderResourceItemDto> = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
if row.resource_type == "folder" {
|
||||
let dto = FolderDto {
|
||||
id: row.id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path: String::new(), // cleared — share recipients must not see hierarchy
|
||||
parent_id: row.parent_id.map(|u| u.to_string()),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
created_at: row.created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
is_root: false,
|
||||
icon_class: Arc::from("fas fa-folder"),
|
||||
icon_special_class: Arc::from("folder-icon"),
|
||||
category: Arc::from("Folder"),
|
||||
};
|
||||
FolderResourceItemDto {
|
||||
resource_type: ResourceTypeDto::Folder,
|
||||
resource: ResourceContentDto::Folder(dto),
|
||||
}
|
||||
} else {
|
||||
let mime = row
|
||||
.mime_type
|
||||
.as_deref()
|
||||
.unwrap_or("application/octet-stream");
|
||||
let size_bytes = row.size.max(0) as u64;
|
||||
let dto = FileDto {
|
||||
id: row.id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path: String::new(),
|
||||
size: size_bytes,
|
||||
mime_type: Arc::from(mime),
|
||||
folder_id: row.parent_id.map(|u| u.to_string()),
|
||||
created_at: row.created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
icon_class: Arc::from(icon_class_for(&row.name, mime)),
|
||||
icon_special_class: Arc::from(icon_special_class_for(&row.name, mime)),
|
||||
category: Arc::from(category_for(&row.name, mime)),
|
||||
size_formatted: format_file_size(size_bytes),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
sort_date: None,
|
||||
etag: String::new(),
|
||||
};
|
||||
FolderResourceItemDto {
|
||||
resource_type: ResourceTypeDto::File,
|
||||
resource: ResourceContentDto::File(dto),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(FolderResourcesDto::with_cursor(items, next_cursor)),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => AppError::from(e).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,16 +341,18 @@ pub async fn list_shared_with_me(
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Decode cursor — discard it when the sort dimension changed to avoid
|
||||
// keyset confusion across sort modes.
|
||||
let reverse = q.reverse;
|
||||
|
||||
// Decode cursor — discard it when the sort dimension or direction changed
|
||||
// to avoid keyset confusion across sort modes.
|
||||
let cursor = q
|
||||
.decode_cursor::<GrantCursor>()
|
||||
.filter(|c| c.sort_by == sort_by);
|
||||
.filter(|c| c.sort_by == sort_by && c.reverse == reverse);
|
||||
|
||||
// Fetch paged summaries from the ACL engine.
|
||||
let (summaries, next_cursor) = match state
|
||||
.authorization
|
||||
.list_incoming_resources_paged(subject, &kinds, limit, cursor, sort_by)
|
||||
.list_incoming_resources_paged(subject, &kinds, limit, cursor, sort_by, reverse)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
|
||||
@@ -8,8 +8,18 @@ use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::FolderDto;
|
||||
use crate::application::dtos::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::application::dtos::recent_dto::{
|
||||
RecentResourceItemDto, RecentResourcesDto, RecentResourcesQuery,
|
||||
};
|
||||
use crate::application::ports::recent_ports::RecentItemsUseCase;
|
||||
use crate::application::services::recent_service::RecentService;
|
||||
use crate::interfaces::errors::AppError;
|
||||
use crate::interfaces::middleware::auth::AuthUser;
|
||||
|
||||
/// Query parameters for getting recent items
|
||||
@@ -19,7 +29,8 @@ pub struct GetRecentParams {
|
||||
limit: Option<i32>,
|
||||
}
|
||||
|
||||
/// Get user's recent items
|
||||
/// Get user's recent items (deprecated — use `GET /api/recent/resources` instead)
|
||||
#[deprecated = "Use GET /api/recent/resources instead"]
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/recent",
|
||||
@@ -213,3 +224,121 @@ pub async fn clear_recent_items(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// List recently accessed resources with cursor pagination.
|
||||
///
|
||||
/// Sorted by `accessed_at` DESC by default (most recently accessed first).
|
||||
/// `path` is cleared when the resource is not owned by the requesting user.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/recent/resources",
|
||||
params(RecentResourcesQuery),
|
||||
responses(
|
||||
(status = 200, description = "Paginated list of recently accessed resources",
|
||||
body = RecentResourcesDto),
|
||||
(status = 400, description = "Invalid cursor or query parameters"),
|
||||
),
|
||||
security(("bearerAuth" = [])),
|
||||
tag = "recent"
|
||||
)]
|
||||
pub async fn list_recent_resources(
|
||||
State(recent_service): State<Arc<RecentService>>,
|
||||
auth_user: AuthUser,
|
||||
Query(q): Query<RecentResourcesQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let user_id = auth_user.id;
|
||||
|
||||
let order_by = q.order_by.as_deref().unwrap_or("accessed_at").to_owned();
|
||||
|
||||
// If a cursor exists, validate that it matches the requested sort/direction.
|
||||
let cursor = q
|
||||
.decode_cursor()
|
||||
.filter(|c| c.order_by == order_by && c.reverse == q.reverse);
|
||||
|
||||
let kinds = q.resource_kinds();
|
||||
|
||||
match recent_service
|
||||
.list_resources_paged(
|
||||
user_id,
|
||||
q.limit_clamped(),
|
||||
cursor,
|
||||
&order_by,
|
||||
kinds.as_deref(),
|
||||
q.reverse,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((rows, next_cursor)) => {
|
||||
let items: Vec<RecentResourceItemDto> = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
// Path is only shown to the owner; non-owners see ""
|
||||
// to avoid leaking another user's folder hierarchy.
|
||||
let path = if row.is_owner {
|
||||
row.path.clone().unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
if row.resource_type == "folder" {
|
||||
let dto = FolderDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path,
|
||||
parent_id: row.parent_id.map(|u| u.to_string()),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
created_at: row.resource_created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
is_root: false,
|
||||
icon_class: std::sync::Arc::from("fas fa-folder"),
|
||||
icon_special_class: std::sync::Arc::from("folder-icon"),
|
||||
category: std::sync::Arc::from("Folder"),
|
||||
};
|
||||
RecentResourceItemDto {
|
||||
resource_type: ResourceTypeDto::Folder,
|
||||
accessed_at: row.accessed_at,
|
||||
resource: ResourceContentDto::Folder(dto),
|
||||
}
|
||||
} else {
|
||||
let mime = row
|
||||
.mime_type
|
||||
.as_deref()
|
||||
.unwrap_or("application/octet-stream");
|
||||
let size_bytes = row.size.max(0) as u64;
|
||||
let dto = FileDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path,
|
||||
size: size_bytes,
|
||||
mime_type: std::sync::Arc::from(mime),
|
||||
folder_id: row.parent_id.map(|u| u.to_string()),
|
||||
created_at: row.resource_created_at.timestamp() as u64,
|
||||
modified_at: row.modified_at.timestamp() as u64,
|
||||
icon_class: std::sync::Arc::from(icon_class_for(&row.name, mime)),
|
||||
icon_special_class: std::sync::Arc::from(icon_special_class_for(
|
||||
&row.name, mime,
|
||||
)),
|
||||
category: std::sync::Arc::from(category_for(&row.name, mime)),
|
||||
size_formatted: format_file_size(size_bytes),
|
||||
owner_id: Some(row.owner_id.to_string()),
|
||||
sort_date: None,
|
||||
etag: String::new(),
|
||||
};
|
||||
RecentResourceItemDto {
|
||||
resource_type: ResourceTypeDto::File,
|
||||
accessed_at: row.accessed_at,
|
||||
resource: ResourceContentDto::File(dto),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(RecentResourcesDto::with_cursor(items, next_cursor)),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(e) => AppError::from(e).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,9 +58,10 @@ use crate::interfaces::api::handlers::file_handler::{
|
||||
delete_file, download_file, get_file_metadata, get_thumbnail, list_files_query,
|
||||
move_file_simple, rename_file, upload_file_with_thumbnails, upload_thumbnail,
|
||||
};
|
||||
#[allow(deprecated)]
|
||||
use crate::interfaces::api::handlers::folder_handler::{
|
||||
create_folder, delete_folder_with_trash, download_folder_zip, get_folder, list_folder_contents,
|
||||
list_folder_contents_paginated, list_folder_listing, list_root_folders,
|
||||
list_folder_contents_paginated, list_folder_listing, list_folder_resources, list_root_folders,
|
||||
list_root_folders_paginated, move_folder, rename_folder,
|
||||
};
|
||||
use crate::interfaces::api::handlers::i18n_handler::{
|
||||
@@ -155,6 +156,9 @@ pub fn create_public_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppStat
|
||||
/// These routes require authentication when auth is enabled.
|
||||
/// Receives the fully-assembled `AppState` and extracts all needed services
|
||||
/// from it, avoiding a long parameter list.
|
||||
// Legacy folder endpoints (contents, listing) are kept for backward-compat;
|
||||
// they are marked #[deprecated] so the OpenAPI spec shows them as deprecated.
|
||||
#[allow(deprecated)]
|
||||
pub fn create_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppState>> {
|
||||
// Extract services from the pre-built AppState
|
||||
let folder_service = app_state.applications.folder_service_concrete.clone();
|
||||
@@ -195,6 +199,7 @@ pub fn create_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppState>> {
|
||||
"/{id}/contents/paginated",
|
||||
get(list_folder_contents_paginated),
|
||||
)
|
||||
.route("/{id}/resources", get(list_folder_resources))
|
||||
.route("/{id}/rename", put(rename_folder))
|
||||
.route("/{id}/move", put(move_folder))
|
||||
.with_state(folder_service.clone());
|
||||
@@ -326,10 +331,14 @@ pub fn create_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppState>> {
|
||||
// Create a router without the i18n routes
|
||||
// Create routes for favorites if the service is available
|
||||
let favorites_router = if let Some(favorites_service) = favorites_service.clone() {
|
||||
use crate::interfaces::api::handlers::favorites_handler;
|
||||
#[allow(deprecated)]
|
||||
use crate::interfaces::api::handlers::favorites_handler::{
|
||||
self, get_favorites, list_favorites_resources,
|
||||
};
|
||||
|
||||
Router::new()
|
||||
.route("/", get(favorites_handler::get_favorites))
|
||||
.route("/", get(get_favorites)) // deprecated, kept for compat
|
||||
.route("/resources", get(list_favorites_resources)) // new cursor-paginated endpoint
|
||||
.route("/batch", post(favorites_handler::batch_add_favorites))
|
||||
.route(
|
||||
"/{item_type}/{item_id}",
|
||||
@@ -346,10 +355,12 @@ pub fn create_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppState>> {
|
||||
|
||||
// Create routes for recent items if the service is available
|
||||
let recent_router = if let Some(recent_service) = recent_service.clone() {
|
||||
#[allow(deprecated)]
|
||||
use crate::interfaces::api::handlers::recent_handler;
|
||||
|
||||
Router::new()
|
||||
.route("/", get(recent_handler::get_recent_items))
|
||||
.route("/resources", get(recent_handler::list_recent_resources))
|
||||
.route(
|
||||
"/{item_type}/{item_id}",
|
||||
post(recent_handler::record_item_access),
|
||||
|
||||
Reference in New Issue
Block a user