feat: improve the file browser with pagination.

This commit is contained in:
arabcoders 2026-02-13 21:46:01 +03:00
parent 19d5d60de1
commit 90e07ce71b
7 changed files with 670 additions and 327 deletions

38
API.md
View file

@ -1576,6 +1576,13 @@ Binary image data with the appropriate `Content-Type`.
**Path Parameter**:
- `path` = Relative path within the download directory (URL-encoded).
**Query Parameters**:
- `page` (optional): Page number (1-indexed). Default: `1`.
- `per_page` (optional): Items per page. Default: `config.default_pagination`, Max: `1000`.
- `sort_by` (optional): Sort field. Options: `name`, `size`, `date`, `type`. Default: `name`.
- `sort_order` (optional): Sort direction. Options: `asc`, `desc`. Default: `asc`.
- `search` (optional): Filter by filename (case-insensitive).
**Response**:
```json
{
@ -1587,12 +1594,12 @@ Binary image data with the appropriate `Content-Type`.
"name": "filename.mp4",
"path": "/filename.mp4",
"size": 123456789,
"mimetype": "mime/type",
"mime": "mime/type",
"mtime": "2023-01-01T12:00:00Z",
"ctime": "2023-01-01T12:00:00Z",
"is_dir": true|false,
"is_file": true|false,
...
"is_symlink": true|false
},
{
"type": "dir",
@ -1601,11 +1608,36 @@ Binary image data with the appropriate `Content-Type`.
"path": "/Season 2025",
...
}
]
],
"pagination": {
"page": 1,
"per_page": 50,
"total": 123,
"total_pages": 3,
"has_next": true,
"has_prev": false
}
}
```
**Examples**:
```bash
# Get first page of root directory
GET /api/file/browser/
# Get second page of videos folder, sorted by size descending
GET /api/file/browser/videos?page=2&sort_by=size&sort_order=desc
# Search for mp4 files
GET /api/file/browser/videos?search=mp4
# Sort by date, newest first
GET /api/file/browser/videos?sort_by=date&sort_order=desc
```
- Returns `403 Forbidden` if file browser is disabled.
- Returns `404 Not Found` if the path doesn't exist.
- Returns `400 Bad Request` if the path is not a directory.
---

View file

@ -814,16 +814,29 @@ def get(
return data
def get_files(base_path: Path | str, dir: str | None = None):
def get_files(
base_path: Path | str,
dir: str | None = None,
page: int = 1,
per_page: int = 0,
sort_by: str = "name",
sort_order: str = "asc",
search: str | None = None,
) -> tuple[list, int]:
"""
Get directory contents.
Get directory contents with optional pagination, sorting, and search.
Args:
base_path (Path|str): Base download path.
dir (str): Directory to check.
page (int): Page number (1-indexed). Ignored if per_page is 0.
per_page (int): Items per page. If 0, returns all items.
sort_by (str): Sort field: name, size, date, type.
sort_order (str): Sort direction: asc, desc.
search (str|None): Filter by filename (case-insensitive).
Returns:
list: List of files and directories.
tuple[list, int]: List of file/directory dicts and total count (before pagination).
Raises:
OSError: If the directory is invalid or not a directory.
@ -909,7 +922,26 @@ def get_files(base_path: Path | str, dir: str | None = None):
}
)
return contents
total: int = len(contents)
if search:
search_lower: str = search.lower()
contents = [c for c in contents if search_lower in c["name"].lower()]
if sort_by == "name":
contents.sort(key=lambda x: x["name"].lower(), reverse=(sort_order.lower() == "desc"))
elif sort_by == "size":
contents.sort(key=lambda x: x["size"], reverse=(sort_order.lower() == "desc"))
elif sort_by == "date":
contents.sort(key=lambda x: x["mtime"], reverse=(sort_order.lower() == "desc"))
elif sort_by == "type":
contents.sort(key=lambda x: x["content_type"], reverse=(sort_order.lower() == "desc"))
if per_page > 0:
offset: int = (page - 1) * per_page
contents = contents[offset : offset + per_page]
return contents, total
def clean_item(item: dict, keys: list | tuple) -> tuple[dict, bool]:

View file

@ -7,6 +7,7 @@ from urllib.parse import unquote_plus
from aiohttp import web
from aiohttp.web import Request, Response
from app.features.core.utils import build_pagination, normalize_pagination
from app.features.streaming.library.ffprobe import ffprobe
from app.library.cache import Cache
from app.library.config import Config
@ -134,16 +135,15 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
req_path: str = request.match_info.get("path")
req_path: str = "/" if not req_path else unquote_plus(req_path)
# Normalize requested path to always be inside download root.
raw_req: str = (req_path or "").strip()
root_dir: Path = Path(config.download_path).resolve()
if raw_req in ("", "/"):
test: Path = root_dir
rel_for_listing = "/"
rel_for_listing: str = "/"
else:
# Strip leading slash so joinpath doesn't ignore the base path.
test = root_dir.joinpath(raw_req.lstrip("/")).resolve(strict=False)
rel_for_listing = raw_req.lstrip("/")
rel_for_listing: str = raw_req.lstrip("/")
try:
test.relative_to(root_dir)
@ -163,10 +163,34 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
)
try:
page, per_page = normalize_pagination(request)
sort_by: str = request.query.get("sort_by", "name")
sort_order: str = request.query.get("sort_order", "asc")
search: str | None = request.query.get("search")
if sort_by not in ("name", "size", "date", "type"):
sort_by = "name"
if sort_order not in ("asc", "desc"):
sort_order = "asc"
contents, total = get_files(
base_path=root_dir,
dir=rel_for_listing,
page=page,
per_page=per_page,
sort_by=sort_by,
sort_order=sort_order,
search=search,
)
total_pages: int = (total + per_page - 1) // per_page if total > 0 else 1
return web.json_response(
data={
"path": rel_for_listing,
"contents": get_files(base_path=root_dir, dir=rel_for_listing),
"contents": contents,
"pagination": build_pagination(total, page, per_page, total_pages),
},
status=web.HTTPOk.status_code,
dumps=encoder.encode,

View file

@ -1488,13 +1488,13 @@ class TestGetFiles:
def test_get_files_root(self):
"""Test getting files from root directory."""
result = get_files(self.base_path)
result, total = get_files(self.base_path)
assert isinstance(result, list)
assert len(result) > 0
def test_get_files_subdir(self):
"""Test getting files from subdirectory."""
result = get_files(self.base_path, "subdir")
result, total = get_files(self.base_path, "subdir")
assert isinstance(result, list)

View file

@ -0,0 +1,406 @@
import { ref, readonly, computed, toRaw } from 'vue'
import { useNotification } from '~/composables/useNotification'
import { useConfigStore } from '~/stores/ConfigStore'
import { request, parse_api_error, sTrim, encodePath } from '~/utils'
import type { FileItem, Pagination } from '~/types/filebrowser'
const items = ref<FileItem[]>([])
const path = ref<string>('/')
const pagination = ref<Pagination>({
page: 1,
per_page: 50,
total: 0,
total_pages: 0,
has_next: false,
has_prev: false,
})
const isLoading = ref<boolean>(false)
const lastError = ref<string | null>(null)
const selectedElms = ref<string[]>([])
const masterSelectAll = ref<boolean>(false)
const sort_by = ref<string>('name')
const sort_order = ref<string>('asc')
const search = ref<string>('')
const throwInstead = ref(false)
const notify = useNotification()
const readJson = async (response: Response): Promise<unknown> => {
try {
const clone = response.clone()
return await clone.json()
}
catch {
return null
}
}
const ensureSuccess = async (response: Response): Promise<void> => {
if (response.ok) {
return
}
const payload = await readJson(response)
const message = await parse_api_error(payload)
throw new Error(message)
}
const handleError = (error: unknown): void => {
const message = error instanceof Error ? error.message : 'Unexpected error occurred.'
lastError.value = message
notify.error(message)
}
const buildQueryParams = (page?: number): string => {
const config = useConfigStore()
const params = new URLSearchParams()
params.set('page', String(page ?? pagination.value.page))
params.set('per_page', String(config.app.default_pagination || 50))
params.set('sort_by', sort_by.value)
params.set('sort_order', sort_order.value)
if (search.value) {
params.set('search', search.value)
}
return params.toString()
}
const loadContents = async (dir: string = '/', page: number = 1): Promise<boolean> => {
isLoading.value = true
try {
if (typeof dir !== 'string') {
dir = '/'
}
dir = encodePath(sTrim(dir, '/'))
const query = buildQueryParams(page)
const response = await request(`/api/file/browser/${sTrim(dir, '/')}?${query}`)
await ensureSuccess(response)
const data = await response.json()
items.value = data.contents || []
path.value = data.path || '/'
if (data.pagination) {
pagination.value = data.pagination
}
selectedElms.value = []
masterSelectAll.value = false
lastError.value = null
return true
}
catch (error) {
handleError(error)
if (throwInstead.value) throw error
return false
}
finally {
isLoading.value = false
}
}
const changeSort = async (by: string): Promise<void> => {
if (!['name', 'size', 'date', 'type'].includes(by)) {
return
}
if (by !== sort_by.value) {
sort_by.value = by
}
else {
sort_order.value = sort_order.value === 'asc' ? 'desc' : 'asc'
}
await loadContents(path.value, 1)
}
const setSearch = async (value: string): Promise<void> => {
search.value = value
await loadContents(path.value, 1)
}
const setSortBy = (value: string): void => {
sort_by.value = value
}
const setSortOrder = (value: string): void => {
sort_order.value = value
}
const setSearchValue = (value: string): void => {
search.value = value
}
const setPage = (value: number): void => {
pagination.value.page = value
}
const changePage = async (page: number): Promise<void> => {
await loadContents(path.value, page)
}
const performAction = async (
item: FileItem,
action: string,
payload: Record<string, unknown>,
callback?: (item: FileItem, action: string, data: Record<string, unknown>, source: FileItem) => void,
multiple: boolean = false
): Promise<boolean> => {
try {
const response = await request('/api/file/actions', {
method: 'POST',
body: JSON.stringify([{ path: item.path, action, ...payload }]),
})
await ensureSuccess(response)
const results = await response.json() as Array<{ path: string, status: boolean, error?: string, [key: string]: unknown }>
for (const result of results) {
if (!multiple && result.path !== item.path) {
continue
}
if (!multiple && !result.status) {
notify.error(`Failed to perform action: ${result.error || 'Unknown error'}`)
return false
}
if (callback && typeof callback === 'function') {
if (!multiple) {
callback(item, action, payload as Record<string, unknown>, item)
}
else {
const matchedItem = items.value.find(it => it.path === result.path)
if (matchedItem) {
callback(matchedItem, action, result as Record<string, unknown>, toRaw(item))
}
}
}
}
return true
}
catch (error) {
handleError(error)
if (throwInstead.value) throw error
return false
}
}
const performMassAction = async (
actions: Array<{ path: string, action: string, [key: string]: unknown }>,
callback?: (result: { path: string, status: boolean, error?: string }) => void
): Promise<boolean> => {
try {
const response = await request('/api/file/actions', {
method: 'POST',
body: JSON.stringify(actions),
})
await ensureSuccess(response)
const results = await response.json() as Array<{ path: string, status: boolean, error?: string }>
for (const result of results) {
if (!result.status) {
notify.error(`Failed to perform action on '${result.path}': ${result.error || 'Unknown error'}`)
continue
}
if (callback && typeof callback === 'function') {
callback(result)
}
}
return true
}
catch (error) {
handleError(error)
if (throwInstead.value) throw error
return false
}
}
const createDirectory = async (dir: string, newDir: string): Promise<boolean> => {
const trimmedDir = sTrim(newDir, '/')
if (!trimmedDir || trimmedDir === dir) {
return false
}
const success = await performAction(
{ path: dir || '/' } as FileItem,
'directory',
{ new_dir: trimmedDir },
() => {
notify.success(`Successfully created '${trimmedDir}'.`)
}
)
return success
}
const renameItem = async (item: FileItem, newName: string): Promise<boolean> => {
const trimmedName = newName.trim()
if (!trimmedName || trimmedName === item.name) {
return false
}
return await performAction(
item,
'rename',
{ new_name: trimmedName },
(it, _, data) => {
const source = data as { new_path?: string }
if (source.new_path) {
it.name = source.new_path.split('/').pop() || trimmedName
it.path = source.new_path
}
notify.success(`Renamed '${item.name}'.`)
},
true
)
}
const deleteItem = async (item: FileItem): Promise<boolean> => {
return await performAction(
item,
'delete',
{},
() => {
items.value = items.value.filter(i => i.path !== item.path)
notify.warning(`Deleted '${item.name}'.`)
}
)
}
const moveItem = async (item: FileItem, newPath: string): Promise<boolean> => {
const trimmedPath = sTrim(newPath, '/') || '/'
if (!trimmedPath || trimmedPath === item.path) {
return false
}
return await performAction(
item,
'move',
{ new_path: trimmedPath },
(it, _, data) => {
const source = data as { new_path?: string; path?: string }
if (source.path) {
items.value = items.value.filter(i => i.path !== source.path)
}
notify.success(`Moved '${item.name}' to '${trimmedPath}'.`)
},
true
)
}
const deleteSelected = async (): Promise<boolean> => {
if (selectedElms.value.length < 1) {
notify.error('No items selected.')
return false
}
const actions = selectedElms.value.map(p => {
return { path: p, action: 'delete' }
})
const success = await performMassAction(actions, (result) => {
const item = items.value.find(it => it.path === result.path)
if (item) {
items.value = items.value.filter(it => it.path !== result.path)
notify.warning(`Deleted '${item.name}'.`)
}
})
if (success) {
selectedElms.value = []
}
return success
}
const moveSelected = async (newPath: string): Promise<boolean> => {
if (selectedElms.value.length < 1) {
notify.error('No items selected.')
return false
}
const trimmedPath = sTrim(newPath, '/') || '/'
const actions = selectedElms.value.map(p => ({
path: p,
action: 'move',
new_path: trimmedPath,
}))
const success = await performMassAction(actions, (result) => {
items.value = items.value.filter(it => it.path !== result.path)
notify.success(`Moved '${result.path}' to '${trimmedPath}'.`)
})
if (success) {
selectedElms.value = []
}
return success
}
const clearError = (): void => {
lastError.value = null
}
const reset = (): void => {
items.value = []
path.value = '/'
pagination.value = {
page: 1,
per_page: 50,
total: 0,
total_pages: 0,
has_next: false,
has_prev: false,
}
selectedElms.value = []
masterSelectAll.value = false
search.value = ''
lastError.value = null
}
const filteredItems = computed<FileItem[]>(() => {
return items.value
})
export const useBrowser = () => ({
items: readonly(items),
path: readonly(path),
pagination: readonly(pagination),
isLoading: readonly(isLoading),
lastError: readonly(lastError),
selectedElms,
masterSelectAll,
sort_by,
sort_order,
search,
filteredItems,
loadContents,
changeSort,
setSearch,
setSortBy,
setSortOrder,
setSearchValue,
setPage,
changePage,
createDirectory,
renameItem,
deleteItem,
moveItem,
deleteSelected,
moveSelected,
performAction,
performMassAction,
clearError,
reset,
throwInstead,
})

View file

@ -5,8 +5,8 @@
<span class="title is-4">
<nav class="breadcrumb is-inline-block">
<ul>
<li v-for="(item, index) in makeBreadCrumb(path)" :key="item.link"
:class="{ 'is-active': index === makeBreadCrumb(path).length - 1 }">
<li v-for="(item, index) in makeBreadCrumb(browserPath)" :key="item.link"
:class="{ 'is-active': index === makeBreadCrumb(browserPath).length - 1 }">
<a :href="item.link" @click.prevent="reloadContent(item.path)" v-text="item.name" />
</li>
<li class="is-active" v-if="isLoading">
@ -19,14 +19,14 @@
</span>
<div class="is-pulled-right">
<div class="field is-grouped">
<div class="control has-icons-left" v-if="show_filter && items && items.length > 0">
<input type="search" v-model.lazy="search" class="input" id="search" placeholder="Filter">
<div class="control has-icons-left" v-if="show_filter">
<input type="search" v-model.lazy="localSearch" class="input" id="search" placeholder="Filter">
<span class="icon is-left">
<i class="fas fa-filter"></i>
</span>
</div>
<div class="control" v-if="items && items.length > 0">
<div class="control">
<button class="button is-danger is-light" @click="toggleFilter">
<span class="icon"><i class="fas fa-filter" /></span>
<span v-if="!isMobile">Filter</span>
@ -34,7 +34,7 @@
</div>
<p class="control">
<button class="button is-info is-light" @click="createDirectory(path)"
<button class="button is-info is-light" @click="handleCreateDirectory"
v-if="config.app.browser_control_enabled">
<span class="icon"><i class="fas fa-folder-plus" /></span>
<span v-if="!isMobile">New Folder</span>
@ -50,10 +50,10 @@
</span>
</button>
</p>
<p class="control" v-if="items && items.length > 0">
<p class="control" v-if="filteredItems && filteredItems.length > 0">
<Dropdown label="Sort&nbsp;&nbsp;" icons="fa-solid fa-sort" :hide_label_on_mobile="true">
<NuxtLink class="dropdown-item" :class="{ 'is-active': 'type' === sort_by }"
@click="changeSort('type')">
@click="handleChangeSort('type')">
<span class="icon"><i class="fa-solid fa-hashtag" /></span>
<span>Type</span>
<span class="icon is-pulled-right" v-if="'type' === sort_by">
@ -63,7 +63,7 @@
</NuxtLink>
<NuxtLink class="dropdown-item" :class="{ 'is-active': 'name' === sort_by }"
@click="changeSort('name')">
@click="handleChangeSort('name')">
<span class="icon"><i class="fa-solid fa-arrow-down-a-z" /></span>
<span>Name</span>
<span class="icon is-pulled-right" v-if="'name' === sort_by">
@ -73,7 +73,7 @@
</NuxtLink>
<NuxtLink class="dropdown-item" :class="{ 'is-active': 'size' === sort_by }"
@click="changeSort('size')">
@click="handleChangeSort('size')">
<span class="icon"><i class="fa-solid fa-weight" /></span>
<span>Size</span>
<span class="icon is-pulled-right" v-if="'size' === sort_by">
@ -83,7 +83,7 @@
</NuxtLink>
<NuxtLink class="dropdown-item" :class="{ 'is-active': 'date' === sort_by }"
@click="changeSort('date')">
@click="handleChangeSort('date')">
<span class="icon"><i class="fa-solid fa-calendar" /></span>
<span>Date</span>
<span class="icon is-pulled-right" v-if="'date' === sort_by">
@ -94,7 +94,7 @@
</Dropdown>
</p>
<p class="control">
<button class="button is-info" @click="reloadContent(path, true)" :class="{ 'is-loading': isLoading }"
<button class="button is-info" @click="reloadContent(browserPath)" :class="{ 'is-loading': isLoading }"
:disabled="isLoading">
<span class="icon"><i class="fas fa-refresh" /></span>
<span v-if="!isMobile">Reload</span>
@ -106,11 +106,11 @@
</div>
<div class="columns is-mobile is-multiline is-justify-content-flex-end"
v-if="config.app.browser_control_enabled && items && items.length > 0">
v-if="config.app.browser_control_enabled && filteredItems && filteredItems.length > 0">
<div class="column is-narrow">
<button type="button" class="button" @click="masterSelectAll = !masterSelectAll"
:class="{ 'has-text-primary': !masterSelectAll, 'has-text-danger': masterSelectAll }"
:disabled="isLoading || items.length < 1">
:disabled="isLoading || filteredItems.length < 1">
<span class="icon">
<i :class="!masterSelectAll ? 'fa-regular fa-square-check' : 'fa-regular fa-square'" />
</span>
@ -124,13 +124,13 @@
<div class="column is-2-tablet is-5-mobile">
<Dropdown label="Actions" icons="fa-solid fa-list">
<a class="dropdown-item has-text-danger"
@click="(selectedElms.length > 0 && !isLoading) ? deleteSelected() : null"
@click="(selectedElms.length > 0 && !isLoading) ? handleDeleteSelected() : null"
:style="{ opacity: (selectedElms.length < 1 || isLoading) ? 0.5 : 1, cursor: (selectedElms.length < 1 || isLoading) ? 'not-allowed' : 'pointer' }">
<span class="icon"><i class="fa-solid fa-trash-can" /></span>
<span>Delete{{ selectedElms.length > 0 ? ` (${selectedElms.length})` : '' }}</span>
</a>
<a class="dropdown-item has-text-link"
@click="(selectedElms.length > 0 && !isLoading) ? moveSelected() : null"
@click="(selectedElms.length > 0 && !isLoading) ? handleMoveSelected() : null"
:style="{ opacity: (selectedElms.length < 1 || isLoading) ? 0.5 : 1, cursor: (selectedElms.length < 1 || isLoading) ? 'not-allowed' : 'pointer' }">
<span class="icon"><i class="fa-solid fa-arrows-alt" /></span>
<span>Move{{ selectedElms.length > 0 ? ` (${selectedElms.length})` : '' }}</span>
@ -139,6 +139,13 @@
</div>
</div>
<div class="columns is-multiline" v-if="pagination.total_pages > 1">
<div class="column is-12">
<Pager :page="pagination.page" :last_page="pagination.total_pages" :isLoading="isLoading"
@navigate="handlePageChange" />
</div>
</div>
<div class="columns is-multiline">
<template v-if="'list' === display_style">
<div class="column is-12" v-if="filteredItems && filteredItems.length > 0">
@ -194,11 +201,11 @@
<td class="is-text-overflow is-vcentered">
<div class="field is-grouped">
<div class="control is-text-overflow is-expanded">
<a :href="uri(`/browser/${item.path}`)" v-if="'dir' === item.content_type"
<a :href="uri(`/browser/${item.path}`)" v-if="'dir' === item.content_type" v-tooltip="item.name"
@click.prevent="handleClick(item)">
{{ item.name }}
</a>
<a :href="makeDownload({}, { filename: item.path, folder: '' })"
<a :href="makeDownload({}, { filename: item.path, folder: '' })" v-tooltip="item.name"
@click.prevent="handleClick(item)" v-else>
{{ item.name }}
</a>
@ -341,16 +348,16 @@
</div>
</template>
<div class="column is-12" v-if="search && filteredItems.length < 1">
<Message class="is-warning" title="No results" icon="fas fa-filter" :useClose="true" @close="() => search = ''"
v-if="search">
<div class="column is-12" v-if="localSearch && filteredItems.length < 1 && !isLoading">
<Message class="is-warning" title="No results" icon="fas fa-filter" :useClose="true"
@close="() => localSearch = ''">
<p class="is-block">
No results found for '<span class="is-underlined is-bold">{{ search }}</span>'.
No results found for '<span class="is-underlined is-bold">{{ localSearch }}</span>'.
</p>
</Message>
</div>
<div class="column is-12" v-if="!items || items.length < 1">
<div class="column is-12" v-else-if="!filteredItems || filteredItems.length < 1">
<Message title="Loading content" class="is-info" icon="fas fa-refresh fa-spin" v-if="isLoading">
Loading file browser contents...
</Message>
@ -369,6 +376,13 @@
</div>
</div>
<div class="columns is-multiline" v-if="pagination.total_pages > 1">
<div class="column is-12">
<Pager :page="pagination.page" :last_page="pagination.total_pages" :isLoading="isLoading"
@navigate="handlePageChange" />
</div>
</div>
<div class="modal is-active" v-if="model_item">
<div class="modal-background" @click="closeModel"></div>
<div class="modal-content is-unbounded-model">
@ -389,34 +403,80 @@
<script setup lang="ts">
import moment from 'moment'
import { useStorage } from '@vueuse/core'
import type { FileItem, FileBrowserResponse } from '~/types/filebrowser'
import type { FileItem } from '~/types/filebrowser'
const route = useRoute()
const toast = useNotification()
const config = useConfigStore()
const isMobile = useMediaQuery({ maxWidth: 1024 })
const dialog = useDialog()
const browser = useBrowser()
const isMobile = useMediaQuery({ maxWidth: 1024 })
const bg_enable = useStorage('random_bg', true)
const bg_opacity = useStorage('random_bg_opacity', 0.95)
const sort_by = useStorage('sort_by', 'name')
const sort_order = useStorage('sort_order', 'asc')
const display_style = useStorage<string>('browser_display_style', 'list')
const show_filter = ref<boolean>(false)
const localSearch = ref<string>('')
const selectedElms = ref<string[]>([])
const masterSelectAll = ref(false)
const items = browser.items
const browserPath = browser.path
const pagination = browser.pagination
const isLoading = browser.isLoading
const selectedElms = browser.selectedElms
const masterSelectAll = browser.masterSelectAll
const sort_by = browser.sort_by
const sort_order = browser.sort_order
const filteredItems = browser.filteredItems
const isLoading = ref<boolean>(false)
const items = ref<FileItem[]>([])
const path = ref<string>((() => {
const initialPath = (() => {
const slug = route.params.slug
if (Array.isArray(slug) && slug.length > 0) {
return '/' + slug.join('/')
}
return '/'
})())
const search = ref<string>('')
const show_filter = ref<boolean>(false)
})()
const isUpdating = ref(false)
const buildStateUrl = (dir: string, page?: number): string => {
const params = new URLSearchParams()
const p = page ?? pagination.value.page
if (p > 1) {
params.set('page', String(p))
}
if (sort_by.value !== 'name') {
params.set('sort_by', sort_by.value)
}
if (sort_order.value !== 'asc') {
params.set('sort_order', sort_order.value)
}
if (localSearch.value) {
params.set('search', localSearch.value)
}
const queryString = params.toString()
const normalizedDir = dir.replace(/^\/+/, '').replace(/\/+$/, '')
const basePath = normalizedDir ? `/browser/${normalizedDir}` : '/browser'
return queryString ? `${basePath}?${queryString}` : basePath
}
const syncFromUrl = (): { page: number } => {
const query = route.query
const page = parseInt(query.page as string, 10) || 1
if (query.sort_by && ['name', 'size', 'date', 'type'].includes(query.sort_by as string)) {
browser.setSortBy(query.sort_by as string)
}
if (query.sort_order && ['asc', 'desc'].includes(query.sort_order as string)) {
browser.setSortOrder(query.sort_order as string)
}
if (query.search && typeof query.search === 'string') {
browser.setSearchValue(query.search)
localSearch.value = query.search
show_filter.value = true
}
return { page }
}
const reset_dialog = () => ({
visible: false,
@ -425,9 +485,10 @@ const reset_dialog = () => ({
message: '',
html_message: '',
options: [],
});
})
const dialog_confirm = ref(reset_dialog())
const model_item = ref<any>()
watch(masterSelectAll, v => {
if (v) {
@ -437,52 +498,26 @@ watch(masterSelectAll, v => {
}
})
const filteredItems = computed<FileItem[]>(() => {
if (!search.value) {
return sortedItems(items.value)
}
const searchLower = search.value.toLowerCase()
return sortedItems(items.value.filter((item: FileItem) => deepIncludes(item, searchLower, new WeakSet())))
watch(localSearch, async (val) => {
if (isUpdating.value) return
await browser.setSearch(val)
updateUrl(browserPath.value, 1)
})
const sortedItems = (items: FileItem[]): FileItem[] => {
if (!items || items.length < 1) {
return []
}
if ('name' === sort_by.value) {
return items.sort((a, b) => {
return 'asc' === sort_order.value ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
})
}
if (sort_by.value === 'size') {
return items.sort((a, b) => {
return 'asc' === sort_order.value ? a.size - b.size : b.size - a.size
})
}
if (sort_by.value === 'date') {
return items.sort((a, b) => {
const aDate = new Date(a.mtime)
const bDate = new Date(b.mtime)
return 'asc' === sort_order.value ? aDate.getTime() - bDate.getTime() : bDate.getTime() - aDate.getTime()
})
}
if (sort_by.value === 'type') {
return items.sort((a, b) => {
return 'asc' === sort_order.value ? a.content_type.localeCompare(b.content_type) : b.content_type.localeCompare(a.content_type)
})
}
return items
}
const model_item = ref<any>()
const closeModel = (): void => { model_item.value = null }
const updateUrl = (dir: string, page?: number): void => {
const normalizedDir = dir.replace(/^\/+/, '').replace(/\/+$/, '')
const displayDir = normalizedDir ? normalizedDir : '/'
const title = `File Browser: /${sTrim(displayDir, '/')}`
const stateUrl = buildStateUrl(dir, page)
const fullUrl = window.location.origin + stateUrl
if (fullUrl !== window.location.href) {
history.replaceState({ path: normalizedDir || '/', title: title }, title, stateUrl)
}
useHead({ title: decodeURIComponent(title) })
}
const handleClick = (item: FileItem): void => {
if (true === ['video', 'audio'].includes(item.content_type)) {
model_item.value = {
@ -515,8 +550,8 @@ const handleClick = (item: FileItem): void => {
}
if ('dir' === item.content_type) {
if (search.value) {
search.value = ''
if (localSearch.value) {
localSearch.value = ''
show_filter.value = false
}
@ -528,63 +563,38 @@ const handleClick = (item: FileItem): void => {
}
const reloadContent = async (dir: string = '/', fromMounted: boolean = false): Promise<void> => {
isUpdating.value = true
try {
isLoading.value = true
const page = fromMounted ? syncFromUrl().page : 1
const success = await browser.loadContents(dir, page)
if (typeof dir !== 'string') {
dir = '/'
}
dir = encodePath(sTrim(dir, '/'))
const response = await request(`/api/file/browser/${sTrim(dir, '/')}`)
if (fromMounted && !response.ok) {
if (fromMounted && !success) {
return
}
items.value = []
search.value = ''
selectedElms.value = []
show_filter.value = false
masterSelectAll.value = false
const data = await response.json() as FileBrowserResponse
if (!data?.contents || data.contents.length > 0) {
items.value = data.contents
}
if (data?.path) {
path.value = sTrim(data.path, '/')
}
const title = `File Browser: /${dir}`
const stateUrl = uri(`/browser/${dir}`)
if (false === fromMounted) {
history.pushState({ path: dir, title: title }, title, stateUrl)
}
useHead({ title: decodeURIComponent(title) })
} catch (e: any) {
if (fromMounted) {
return
}
console.error(e)
toast.error('Failed to load file browser contents.')
updateUrl(dir, page)
} finally {
isLoading.value = false
isUpdating.value = false
}
}
const handlePageChange = async (page: number): Promise<void> => {
await browser.changePage(page)
updateUrl(browserPath.value, page)
}
const handleChangeSort = async (by: string): Promise<void> => {
await browser.changeSort(by)
updateUrl(browserPath.value, 1)
}
const event_handler = (e: Event): void => {
const evt = e as PopStateEvent
if (!evt.state) {
return
}
if (evt.state.path === path.value || evt.state.path === window.location.pathname) {
if (evt.state.path === browserPath.value && window.location.search === route.fullPath.split('?')[1]) {
return
}
@ -593,7 +603,7 @@ const event_handler = (e: Event): void => {
onMounted(async () => {
document.addEventListener('popstate', event_handler as EventListener)
await reloadContent(path.value, true)
await reloadContent(initialPath, true)
})
onBeforeUnmount(() => document.removeEventListener('popstate', event_handler as EventListener))
@ -610,7 +620,6 @@ const makeBreadCrumb = (path: string): { name: string, link: string, path: strin
path: baseLink
})
// -- explode path and create links
const parts = path.split('/')
parts.forEach((part, index) => {
const path = baseLink + parts.slice(0, index + 1).join('/')
@ -655,36 +664,24 @@ const setIcon = (item: FileItem): string => {
return 'fa-file'
}
const changeSort = (by: string): void => {
if (!['name', 'size', 'date', 'type'].includes(by)) {
return
}
if (by !== sort_by.value) {
sort_by.value = by
}
sort_order.value = 'asc' === sort_order.value ? 'desc' : 'asc'
}
const toggleFilter = (): void => {
show_filter.value = !show_filter.value
if (!show_filter.value) {
search.value = ''
localSearch.value = ''
return
}
awaitElement('#search', (e: Element) => (e as HTMLElement).focus())
}
const createDirectory = async (dir: string): Promise<void> => {
const handleCreateDirectory = async (): Promise<void> => {
if (!config.app.browser_control_enabled) {
return
}
const { status, value: newDir } = await dialog.promptDialog({
title: 'Create New Directory',
message: `Enter name for new directory in '${dir || '/'}':`,
message: `Enter name for new directory in '${browserPath.value || '/'}':`,
initial: '',
confirmText: 'Create',
cancelText: 'Cancel',
@ -694,15 +691,10 @@ const createDirectory = async (dir: string): Promise<void> => {
return
}
const new_dir = sTrim(newDir, '/')
if (!new_dir || new_dir === dir) {
return
const success = await browser.createDirectory(browserPath.value, newDir)
if (success) {
await reloadContent(browserPath.value, true)
}
await actionRequest({ path: dir || '/' } as FileItem, 'directory', { new_dir: new_dir }, (_item, _action, _data) => {
reloadContent(path.value, true)
toast.success(`Successfully created '${new_dir}'.`)
})
}
const handleAction = async (action: string, item: FileItem): Promise<void> => {
@ -723,18 +715,10 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
return
}
const new_name = newName.trim()
if (!new_name || new_name === item.name) {
return
const success = await browser.renameItem(item, newName)
if (success) {
await reloadContent(browserPath.value, true)
}
await actionRequest(item, 'rename', { new_name: new_name }, (item, _, data, source) => {
if (item.path === source.path) {
toast.success(`Renamed '${item.name}'.`)
}
item.name = basename(data.new_path)
item.path = data.new_path
}, true)
return
}
@ -752,11 +736,7 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
return
}
await actionRequest(item, 'delete', {}, (item, _action, _data) => {
items.value = items.value.filter(i => i.path !== item.path)
toast.warning(`Deleted '${item.name}'.`)
})
await browser.deleteItem(item)
return
}
@ -774,120 +754,15 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
return
}
const new_path = sTrim(newPath, '/') || '/'
if (!new_path || new_path === item.path) {
return
const success = await browser.moveItem(item, newPath)
if (success) {
await reloadContent(browserPath.value, true)
}
await actionRequest(item, 'move', { new_path: new_path }, (item, _, data, source) => {
if (item.path === source.path) {
toast.success(`Moved '${item.name}' to '${data.new_path}'.`)
}
items.value = items.value.filter(i => i.path !== data.path)
}, true)
return
}
}
const actionRequest = async (
item: FileItem,
action: string,
req: Record<string, any>,
cb: (item: FileItem, action: string, data: any, source: FileItem, req: any) => void,
multiple: boolean = false
): Promise<any> => {
if (!config.app.browser_control_enabled) {
return
}
if (!item || !action || !req) {
return
}
try {
const response = await request(`/api/file/actions`, {
method: 'POST',
body: JSON.stringify([{ path: item.path, action: action, ...req }]),
})
if (!response.ok) {
const error = await response.json()
toast.error(`Failed to perform action: ${error.error || 'Unknown error'}`)
return
}
const json = await response.json() as Array<{ path: string, status: boolean, error?: string }>
json.forEach(i => {
if (false === multiple && i.path !== item.path) {
return
}
if (false === multiple && true !== i.status) {
toast.error(`Failed to perform action: ${i.error || 'Unknown error'}`)
return
}
if (cb && typeof cb === 'function') {
if (false === multiple) {
return cb(item, action, req, item, req)
}
items.value.forEach(it => {
if (it.path === i.path) {
return cb(it, action, i, toRaw(item), req)
}
})
}
});
return response
} catch (error: any) {
console.error(error)
toast.error(`Failed to perform action: ${error.message}`)
}
}
const massAction = async (items: Array<{ path: string, action: string }>, cb: (item: any) => void): Promise<any> => {
if (!config.app.browser_control_enabled) {
return
}
if (!items || items.length < 1) {
return
}
try {
const response = await request(`/api/file/actions`, {
method: 'POST',
body: JSON.stringify(items),
})
if (!response.ok) {
const error = await response.json()
toast.error(`Failed to perform action: ${error.error || 'Unknown error'}`)
return
}
const json = await response.json() as Array<{ path: string, status: boolean, error?: string }>
json.forEach(i => {
if (true !== i.status) {
toast.error(`Failed to perform action on '${i.path}': ${i.error || 'Unknown error'}`)
return
}
if (cb && typeof cb === 'function') {
cb(i)
}
});
return response
} catch (error: any) {
console.error(error)
toast.error(`Failed to perform action: ${error.message}`)
}
}
const deleteSelected = async () => {
const handleDeleteSelected = async () => {
if (selectedElms.value.length < 1) {
toast.error('No items selected.')
return
@ -903,7 +778,6 @@ const deleteSelected = async () => {
return `<li><span class="icon"><i class="fa-solid ${setIcon(item)}"></i></span> <span class="${color}">${item.name}</span></li>`
}).join('') + `</ul>`
const { status } = await dialog.confirmDialog({
title: 'Delete Confirmation',
message: `Delete the following items?`,
@ -918,27 +792,10 @@ const deleteSelected = async () => {
return
}
const actions = [] as Array<{ action: string, path: string }>
selectedElms.value.forEach(p => {
const item = items.value.find(i => i.path === p)
if (!item) {
return;
}
actions.push({ path: item.path, action: 'delete' })
})
await massAction(actions, i => {
const item = items.value.find(it => it.path === i.path)
if (!item) {
return
}
items.value = items.value.filter(it => it.path !== i.path)
toast.warning(`Deleted '${item.name}'.`)
})
await browser.deleteSelected()
}
const moveSelected = async () => {
const handleMoveSelected = async () => {
if (selectedElms.value.length < 1) {
toast.error('No items selected.')
return
@ -947,35 +804,17 @@ const moveSelected = async () => {
const { status, value: newPath } = await dialog.promptDialog({
title: 'Move Items',
message: `Enter new path for selected items:`,
initial: path.value || '/',
initial: browserPath.value || '/',
confirmText: 'Move',
confirmColor: 'is-danger',
cancelText: 'Cancel',
})
if (true !== status || !newPath || newPath === path.value) {
if (true !== status || !newPath || newPath === browserPath.value) {
selectedElms.value = []
return
}
const actions = [] as Array<{ action: string, path: string, new_path: string }>
selectedElms.value.forEach(p => {
const item = items.value.find(i => i.path === p)
if (!item) {
return;
}
actions.push({
path: item.path,
action: 'move',
new_path: sTrim(newPath, '/') || '/',
})
})
await massAction(actions, i => {
items.value = items.value.filter(it => it.path !== i.path)
toast.success(`Moved '${i.path}' to '${sTrim(newPath, '/')}'.`)
})
await browser.moveSelected(newPath)
}
</script>

View file

@ -1,3 +1,12 @@
type Pagination = {
page: number
per_page: number
total: number
total_pages: number
has_next: boolean
has_prev: boolean
}
type FileItem = {
type: 'file' | 'dir' | 'link'
content_type: 'image' | 'video' | 'text' | 'subtitle' | 'metadata' | 'dir' | string
@ -15,6 +24,7 @@ type FileItem = {
type FileBrowserResponse = {
path: string
contents: FileItem[]
pagination: Pagination
}
export type { FileItem, FileBrowserResponse }
export type { FileItem, FileBrowserResponse, Pagination }