wip
This commit is contained in:
parent
e0227c1772
commit
bf1c79577f
5 changed files with 408 additions and 217 deletions
|
|
@ -160,8 +160,8 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
|
||||||
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
||||||
|
|
||||||
|
|
||||||
@route("POST", "api/file/action/{path:.*}", "browser.actions")
|
@route("POST", "api/file/actions", "browser.file.actions")
|
||||||
async def path_action(request: Request, config: Config) -> Response:
|
async def path_actions(request: Request, config: Config) -> Response:
|
||||||
"""
|
"""
|
||||||
Browser actions.
|
Browser actions.
|
||||||
|
|
||||||
|
|
@ -184,134 +184,212 @@ async def path_action(request: Request, config: Config) -> Response:
|
||||||
rootPath: Path = Path(config.download_path)
|
rootPath: Path = Path(config.download_path)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
params = await request.json()
|
actions = await request.json()
|
||||||
if not params or not isinstance(params, dict):
|
if not actions or not isinstance(actions, list):
|
||||||
return web.json_response(data={"error": "Invalid parameters."}, status=web.HTTPBadRequest.status_code)
|
return web.json_response(
|
||||||
|
data={"error": "Invalid parameters expecting list of dicts."}, status=web.HTTPBadRequest.status_code
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOG.exception(e)
|
LOG.exception(e)
|
||||||
return web.json_response(data={"error": "Invalid JSON."}, status=web.HTTPBadRequest.status_code)
|
return web.json_response(data={"error": "Invalid JSON."}, status=web.HTTPBadRequest.status_code)
|
||||||
|
|
||||||
action = params.get("action").lower()
|
# validate each action before performing any operations
|
||||||
if not action:
|
for params in actions:
|
||||||
return web.json_response(data={"error": "Action is required."}, status=web.HTTPBadRequest.status_code)
|
action = params.get("action").lower()
|
||||||
|
if not action or action not in ["rename", "delete", "move", "directory"]:
|
||||||
req_path: str = request.match_info.get("path")
|
|
||||||
req_path: str = "/" if not req_path else unquote_plus(req_path)
|
|
||||||
|
|
||||||
test: Path = Path(config.download_path)
|
|
||||||
if req_path and "/" != req_path:
|
|
||||||
test = test.joinpath(req_path)
|
|
||||||
|
|
||||||
if not test.exists():
|
|
||||||
return web.json_response(
|
|
||||||
data={"error": f"path '{req_path}' does not exist."}, status=web.HTTPNotFound.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
path, status = get_file(download_path=config.download_path, file=str(test.relative_to(config.download_path)))
|
|
||||||
if web.HTTPOk.status_code != status:
|
|
||||||
return web.json_response(
|
return web.json_response(
|
||||||
data={"error": f"File {status}: '{test}' does not exist."}, status=web.HTTPNotFound.status_code
|
data={"error": f"Invalid action '{action}'. Must be one of rename, delete, move, directory."},
|
||||||
)
|
|
||||||
if not path.is_relative_to(rootPath):
|
|
||||||
return web.json_response(
|
|
||||||
data={"error": "Cannot perform actions on files outside the download path."},
|
|
||||||
status=web.HTTPBadRequest.status_code,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
LOG.exception(e)
|
|
||||||
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
|
||||||
|
|
||||||
if "directory" != action:
|
|
||||||
if path == rootPath:
|
|
||||||
return web.json_response(
|
|
||||||
data={"error": "Cannot perform actions on the root directory."}, status=web.HTTPBadRequest.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
if not path.is_relative_to(rootPath):
|
|
||||||
return web.json_response(
|
|
||||||
data={"error": "Cannot perform actions on files outside the download path."},
|
|
||||||
status=web.HTTPBadRequest.status_code,
|
status=web.HTTPBadRequest.status_code,
|
||||||
)
|
)
|
||||||
|
|
||||||
if "rename" == action:
|
if "rename" == action and not params.get("new_name"):
|
||||||
new_name = params.get("new_name")
|
|
||||||
if not new_name:
|
|
||||||
return web.json_response(data={"error": "New name is required."}, status=web.HTTPBadRequest.status_code)
|
|
||||||
|
|
||||||
new_path = path.parent.joinpath(new_name)
|
|
||||||
if new_path.exists():
|
|
||||||
return web.json_response(
|
return web.json_response(
|
||||||
data={"error": f"File '{new_name}' already exists."}, status=web.HTTPConflict.status_code
|
data={"error": "New name is required for rename action."}, status=web.HTTPBadRequest.status_code
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
if "move" == action and not params.get("new_path"):
|
||||||
path.rename(new_path)
|
return web.json_response(
|
||||||
LOG.info(
|
data={"error": "New path is required for move action."}, status=web.HTTPBadRequest.status_code
|
||||||
f"Renamed '{path.relative_to(config.download_path)}' to '{test.relative_to(config.download_path)}'"
|
|
||||||
)
|
)
|
||||||
except OSError as e:
|
|
||||||
LOG.exception(e)
|
|
||||||
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
|
||||||
|
|
||||||
if "delete" == action:
|
if "directory" == action and not params.get("new_dir"):
|
||||||
|
return web.json_response(
|
||||||
|
data={"error": "New directory name is required for directory action."},
|
||||||
|
status=web.HTTPBadRequest.status_code,
|
||||||
|
)
|
||||||
|
|
||||||
|
operations_status: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
def record(
|
||||||
|
op_path: str | Path,
|
||||||
|
*,
|
||||||
|
ok: bool,
|
||||||
|
error: str | None = None,
|
||||||
|
action: str | None = None,
|
||||||
|
extra: dict | None = None,
|
||||||
|
) -> None:
|
||||||
try:
|
try:
|
||||||
if not path.exists():
|
if isinstance(op_path, Path):
|
||||||
return web.json_response(
|
rel: str = str(op_path.relative_to(rootPath)).strip("/")
|
||||||
data={"error": f"Path '{path}' does not exist."}, status=web.HTTPNotFound.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
if path.is_dir():
|
|
||||||
delete_dir(path)
|
|
||||||
else:
|
else:
|
||||||
path.unlink(missing_ok=True)
|
rel: str = str(op_path).strip("/")
|
||||||
|
except Exception:
|
||||||
|
rel = str(op_path)
|
||||||
|
entry: dict = {
|
||||||
|
"path": rel if rel else "/",
|
||||||
|
"status": ok,
|
||||||
|
"error": error,
|
||||||
|
}
|
||||||
|
if action:
|
||||||
|
entry["action"] = action
|
||||||
|
if extra:
|
||||||
|
norm_extra: dict = {}
|
||||||
|
for k, v in extra.items():
|
||||||
|
if isinstance(v, Path):
|
||||||
|
try:
|
||||||
|
norm_extra[k] = str(v.relative_to(rootPath)).strip("/") or "/"
|
||||||
|
except Exception:
|
||||||
|
norm_extra[k] = str(v)
|
||||||
|
else:
|
||||||
|
norm_extra[k] = v
|
||||||
|
entry.update(norm_extra)
|
||||||
|
operations_status.append(entry)
|
||||||
|
|
||||||
LOG.info(f"Deleted '{path.relative_to(config.download_path)}'")
|
# perform each action
|
||||||
except OSError as e:
|
for params in actions:
|
||||||
LOG.exception(e)
|
req_path: str = params.get("path")
|
||||||
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
if not req_path:
|
||||||
|
record("no_path", ok=False, error="Path is required.", extra={"item": params})
|
||||||
|
continue
|
||||||
|
|
||||||
if "move" == action:
|
action: str = params.get("action", "").lower()
|
||||||
new_path = params.get("new_path")
|
if not action:
|
||||||
if not new_path:
|
record(req_path, ok=False, error="Action is required.", extra={"item": params})
|
||||||
return web.json_response(data={"error": "New path is required."}, status=web.HTTPBadRequest.status_code)
|
continue
|
||||||
|
|
||||||
new_path = Path(config.download_path).joinpath(unquote_plus(new_path))
|
req_path: str = "/" if not req_path else unquote_plus(req_path)
|
||||||
if not new_path.exists() or not new_path.is_dir():
|
|
||||||
return web.json_response(
|
test: Path = Path(config.download_path)
|
||||||
data={"error": f"New path '{new_path}' does not exist or is not a directory."},
|
if req_path and "/" != req_path:
|
||||||
status=web.HTTPNotFound.status_code,
|
test = test.joinpath(req_path)
|
||||||
)
|
|
||||||
|
if not test.exists():
|
||||||
|
record(req_path, ok=False, error=f"path '{req_path}' does not exist.", action=action)
|
||||||
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
path.rename(new_path.joinpath(path.name))
|
path, status = get_file(
|
||||||
except OSError as e:
|
download_path=config.download_path, file=str(test.relative_to(config.download_path))
|
||||||
|
)
|
||||||
|
if web.HTTPOk.status_code != status:
|
||||||
|
record(req_path, ok=False, error="Invalid path.", action=action)
|
||||||
|
continue
|
||||||
|
if not path.is_relative_to(rootPath):
|
||||||
|
record(req_path, ok=False, error="Path outside download root.", action=action)
|
||||||
|
continue
|
||||||
|
except Exception as e:
|
||||||
LOG.exception(e)
|
LOG.exception(e)
|
||||||
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
|
record(req_path, ok=False, error=str(e), action=action)
|
||||||
|
continue
|
||||||
|
|
||||||
if "directory" == action:
|
if "directory" != action:
|
||||||
new_dir = params.get("new_dir").lstrip("/").strip()
|
if path == rootPath:
|
||||||
if not new_dir:
|
record(path, ok=False, error="Cannot operate on root directory.", action=action)
|
||||||
return web.json_response(
|
continue
|
||||||
data={"error": "New directory name is required."}, status=web.HTTPBadRequest.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
new_path = path.joinpath(*new_dir.split("/"))
|
if not path.is_relative_to(rootPath):
|
||||||
if new_path.exists():
|
record(path, ok=False, error="Path outside download root.", action=action)
|
||||||
return web.json_response(
|
continue
|
||||||
data={"error": f"Directory '{new_dir}' already exists."}, status=web.HTTPConflict.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
if "rename" == action:
|
||||||
new_path.mkdir(parents=True, exist_ok=True)
|
new_name: str = params.get("new_name")
|
||||||
LOG.info(f"Created directory '{new_path.relative_to(config.download_path)}'")
|
if not new_name:
|
||||||
except OSError as e:
|
record(path, ok=False, error="New name is required for rename action.", action=action)
|
||||||
LOG.exception(e)
|
continue
|
||||||
return web.json_response(
|
|
||||||
data={"error": str(e), "path": str(test)}, status=web.HTTPInternalServerError.status_code
|
|
||||||
)
|
|
||||||
|
|
||||||
return web.Response(status=web.HTTPOk.status_code)
|
new_path: Path = path.parent.joinpath(new_name)
|
||||||
|
if new_path.exists():
|
||||||
|
record(
|
||||||
|
new_path, ok=False, error="Destination already exists.", action=action, extra={"new_path": new_path}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
path.rename(new_path)
|
||||||
|
LOG.info(
|
||||||
|
f"Renamed '{path.relative_to(config.download_path)}' to '{new_path.relative_to(config.download_path)}'"
|
||||||
|
)
|
||||||
|
except OSError as e:
|
||||||
|
LOG.exception(e)
|
||||||
|
record(path, ok=False, error=str(e), action=action, extra={"new_path": new_path})
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
record(path, ok=True, action=action, extra={"new_path": new_path})
|
||||||
|
|
||||||
|
if "delete" == action:
|
||||||
|
try:
|
||||||
|
if not path.exists():
|
||||||
|
record(path, ok=False, error="Path does not exist.", action=action)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if path.is_dir():
|
||||||
|
delete_dir(path)
|
||||||
|
else:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
LOG.info(f"Deleted '{path.relative_to(config.download_path)}'")
|
||||||
|
except OSError as e:
|
||||||
|
LOG.exception(e)
|
||||||
|
record(path, ok=False, error=str(e), action=action)
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
record(path, ok=True, action=action, extra={"deleted": True})
|
||||||
|
|
||||||
|
if "move" == action:
|
||||||
|
new_path = params.get("new_path")
|
||||||
|
if not new_path:
|
||||||
|
record(path, ok=False, error="New path is required for move action.", action=action)
|
||||||
|
continue
|
||||||
|
|
||||||
|
new_path = Path(config.download_path).joinpath(unquote_plus(new_path))
|
||||||
|
if not new_path.exists() or not new_path.is_dir():
|
||||||
|
record(path, ok=False, error="Destination path is invalid.", action=action, extra={"move_to": new_path})
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
dest = new_path.joinpath(path.name)
|
||||||
|
path.rename(dest)
|
||||||
|
except OSError as e:
|
||||||
|
LOG.exception(e)
|
||||||
|
record(path, ok=False, error=str(e), action=action, extra={"moved_to": dest})
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
record(path, ok=True, action=action, extra={"moved_to": dest})
|
||||||
|
|
||||||
|
if "directory" == action:
|
||||||
|
new_dir = params.get("new_dir").lstrip("/").strip()
|
||||||
|
if not new_dir:
|
||||||
|
record(path, ok=False, error="New directory name is required for directory action.", action=action)
|
||||||
|
continue
|
||||||
|
|
||||||
|
new_path = path.joinpath(*new_dir.split("/"))
|
||||||
|
if new_path.exists():
|
||||||
|
record(
|
||||||
|
new_path, ok=False, error="Directory already exists.", action=action, extra={"created": new_path}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
new_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
LOG.info(f"Created directory '{new_path.relative_to(config.download_path)}'")
|
||||||
|
except OSError as e:
|
||||||
|
LOG.exception(e)
|
||||||
|
record(new_path, ok=False, error=str(e), action=action, extra={"created": new_path})
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
record(new_path, ok=True, action=action, extra={"created": new_path})
|
||||||
|
|
||||||
|
return web.json_response(data=operations_status, status=web.HTTPOk.status_code)
|
||||||
|
|
||||||
|
|
||||||
@route("POST", "api/file/download", "browser.download.prepare")
|
@route("POST", "api/file/download", "browser.download.prepare")
|
||||||
|
|
|
||||||
|
|
@ -71,7 +71,9 @@
|
||||||
<template v-else-if="state.current?.type === 'confirm' || state.current?.type === 'prompt'">
|
<template v-else-if="state.current?.type === 'confirm' || state.current?.type === 'prompt'">
|
||||||
<div class="field is-grouped">
|
<div class="field is-grouped">
|
||||||
<div class="control">
|
<div class="control">
|
||||||
<button class="button is-primary" @click="onEnter">
|
<button class="button" @click="onEnter"
|
||||||
|
:class="state.current?.opts.confirmColor ?? 'is-primary'"
|
||||||
|
:disabled="localInput === (state.current?.opts as PromptOptions)?.initial">
|
||||||
<span class="icon-text">
|
<span class="icon-text">
|
||||||
<span class="icon"><i class="fas fa-check" /></span>
|
<span class="icon"><i class="fas fa-check" /></span>
|
||||||
<span>{{ (state.current?.opts as any)?.confirmText ?? 'OK' }}</span>
|
<span>{{ (state.current?.opts as any)?.confirmText ?? 'OK' }}</span>
|
||||||
|
|
@ -97,7 +99,7 @@
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, watch, nextTick, computed } from 'vue'
|
import { ref, watch, nextTick, computed } from 'vue'
|
||||||
import { useDialog } from '~/composables/useDialog'
|
import { useDialog, type PromptOptions } from '~/composables/useDialog'
|
||||||
|
|
||||||
const { state, confirm, cancel } = useDialog()
|
const { state, confirm, cancel } = useDialog()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@
|
||||||
code {
|
code {
|
||||||
color: var(--bulma-code) !important
|
color: var(--bulma-code) !important
|
||||||
}
|
}
|
||||||
|
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
|
|
@ -1,127 +1,131 @@
|
||||||
import {reactive, readonly} from 'vue'
|
import { reactive, readonly } from 'vue'
|
||||||
|
|
||||||
export type DialogResult<T = string | null> = { status: boolean; value: T }
|
export type DialogResult<T = string | null> = { status: boolean; value: T }
|
||||||
|
|
||||||
type BaseOptions = {
|
type BaseOptions = {
|
||||||
/**
|
/**
|
||||||
* Title of the dialog
|
* Title of the dialog
|
||||||
*/
|
*/
|
||||||
title?: string
|
title?: string
|
||||||
/**
|
/**
|
||||||
* Message to display in the dialog
|
* Message to display in the dialog
|
||||||
*/
|
*/
|
||||||
message?: string
|
message?: string
|
||||||
/**
|
/**
|
||||||
* Text for the confirm button
|
* Text for the confirm button
|
||||||
*/
|
*/
|
||||||
confirmText?: string
|
confirmText?: string
|
||||||
|
/**
|
||||||
|
* Color class for the confirm button (e.g., 'is-primary', 'is-danger')
|
||||||
|
*/
|
||||||
|
confirmColor?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PromptOptions = BaseOptions & {
|
export type PromptOptions = BaseOptions & {
|
||||||
/**
|
/**
|
||||||
* Text for the input field
|
* Text for the input field
|
||||||
*/
|
*/
|
||||||
initial?: string
|
initial?: string
|
||||||
/**
|
/**
|
||||||
* Placeholder text for the input field
|
* Placeholder text for the input field
|
||||||
*/
|
*/
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
/**
|
/**
|
||||||
* Text for the cancel button
|
* Text for the cancel button
|
||||||
*/
|
*/
|
||||||
cancelText?: string
|
cancelText?: string
|
||||||
/**
|
/**
|
||||||
* Function to validate the input value
|
* Function to validate the input value
|
||||||
* @returns true if valid, or an error message string if invalid
|
* @returns true if valid, or an error message string if invalid
|
||||||
*/
|
*/
|
||||||
validate?: (v: string) => true | string
|
validate?: (v: string) => true | string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ConfirmOptions = BaseOptions & {
|
export type ConfirmOptions = BaseOptions & {
|
||||||
/**
|
/**
|
||||||
* Text for the confirm button
|
* Text for the confirm button
|
||||||
*/
|
*/
|
||||||
cancelText?: string
|
cancelText?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AlertOptions = BaseOptions & {}
|
export type AlertOptions = BaseOptions & {}
|
||||||
|
|
||||||
type QueueItem = {
|
type QueueItem = {
|
||||||
type: 'prompt' | 'confirm' | 'alert'
|
type: 'prompt' | 'confirm' | 'alert'
|
||||||
opts: PromptOptions | ConfirmOptions | AlertOptions
|
opts: PromptOptions | ConfirmOptions | AlertOptions
|
||||||
resolve: (r: DialogResult<any>) => void
|
resolve: (r: DialogResult<any>) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type DialogState = {
|
type DialogState = {
|
||||||
current: QueueItem | null
|
current: QueueItem | null
|
||||||
queue: QueueItem[]
|
queue: QueueItem[]
|
||||||
errorMsg: string | null
|
errorMsg: string | null
|
||||||
input: string
|
input: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useDialog = () => {
|
export const useDialog = () => {
|
||||||
const raw = useState<DialogState>('dialog:state', () => reactive({
|
const raw = useState<DialogState>('dialog:state', () => reactive({
|
||||||
current: null,
|
current: null,
|
||||||
queue: [],
|
queue: [],
|
||||||
errorMsg: null,
|
errorMsg: null,
|
||||||
input: '',
|
input: '',
|
||||||
} as DialogState))
|
} as DialogState))
|
||||||
|
|
||||||
const state = raw.value
|
const state = raw.value
|
||||||
|
|
||||||
const _dequeue = () => {
|
const _dequeue = () => {
|
||||||
if (!state.current && state.queue.length) {
|
if (!state.current && state.queue.length) {
|
||||||
state.current = state.queue.shift()!
|
state.current = state.queue.shift()!
|
||||||
state.errorMsg = null
|
state.errorMsg = null
|
||||||
state.input = state.current.type === 'prompt' ? (state.current.opts as PromptOptions).initial ?? '' : ''
|
state.input = state.current.type === 'prompt' ? (state.current.opts as PromptOptions).initial ?? '' : ''
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const promptDialog = (opts: PromptOptions) => new Promise<DialogResult<string>>((resolve) => {
|
const promptDialog = (opts: PromptOptions) => new Promise<DialogResult<string>>((resolve) => {
|
||||||
state.queue.push({type: 'prompt', opts, resolve})
|
state.queue.push({ type: 'prompt', opts, resolve })
|
||||||
_dequeue()
|
_dequeue()
|
||||||
})
|
})
|
||||||
|
|
||||||
const confirmDialog = (opts: ConfirmOptions) => new Promise<DialogResult<null>>((resolve) => {
|
const confirmDialog = (opts: ConfirmOptions) => new Promise<DialogResult<null>>((resolve) => {
|
||||||
state.queue.push({type: 'confirm', opts, resolve})
|
state.queue.push({ type: 'confirm', opts, resolve })
|
||||||
_dequeue()
|
_dequeue()
|
||||||
})
|
})
|
||||||
|
|
||||||
const alertDialog = (opts: AlertOptions) => new Promise<DialogResult<null>>((resolve) => {
|
const alertDialog = (opts: AlertOptions) => new Promise<DialogResult<null>>((resolve) => {
|
||||||
state.queue.push({type: 'alert', opts, resolve})
|
state.queue.push({ type: 'alert', opts, resolve })
|
||||||
_dequeue()
|
_dequeue()
|
||||||
})
|
})
|
||||||
|
|
||||||
const confirm = (value?: string) => {
|
const confirm = (value?: string) => {
|
||||||
if (!state.current) return
|
if (!state.current) return
|
||||||
if (state.current.type === 'prompt') {
|
if (state.current.type === 'prompt') {
|
||||||
const val = value ?? state.input
|
const val = value ?? state.input
|
||||||
const v = (state.current.opts as PromptOptions).validate?.(val)
|
const v = (state.current.opts as PromptOptions).validate?.(val)
|
||||||
if (v && v !== true) {
|
if (v && v !== true) {
|
||||||
state.errorMsg = v
|
state.errorMsg = v
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
state.current.resolve({status: true, value: val})
|
state.current.resolve({ status: true, value: val })
|
||||||
} else {
|
} else {
|
||||||
state.current.resolve({status: true, value: null})
|
state.current.resolve({ status: true, value: null })
|
||||||
}
|
|
||||||
state.current = null
|
|
||||||
_dequeue()
|
|
||||||
}
|
}
|
||||||
|
state.current = null
|
||||||
|
_dequeue()
|
||||||
|
}
|
||||||
|
|
||||||
const cancel = () => {
|
const cancel = () => {
|
||||||
if (!state.current) return
|
if (!state.current) return
|
||||||
state.current.resolve({status: false, value: null})
|
state.current.resolve({ status: false, value: null })
|
||||||
state.current = null
|
state.current = null
|
||||||
_dequeue()
|
_dequeue()
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
promptDialog,
|
promptDialog,
|
||||||
confirmDialog,
|
confirmDialog,
|
||||||
alertDialog,
|
alertDialog,
|
||||||
confirm,
|
confirm,
|
||||||
cancel,
|
cancel,
|
||||||
state: readonly(state) as Readonly<DialogState>,
|
state: readonly(state) as Readonly<DialogState>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,26 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="columns is-multiline"
|
||||||
|
v-if="items && items.length > 0 && selectedElms.length > 0 && config.app.browser_control_enabled">
|
||||||
|
<div class="column is-half-mobile">
|
||||||
|
<button type="button" class="button is-fullwidth is-danger" @click="confirm_delete">
|
||||||
|
<span class="icon-text is-block">
|
||||||
|
<span class="icon"><i class="fa-solid fa-trash-can" /></span>
|
||||||
|
<span>Delete selected</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="column is-half-mobile">
|
||||||
|
<button type="button" class="button is-fullwidth is-link">
|
||||||
|
<span class="icon-text is-block">
|
||||||
|
<span class="icon"><i class="fa-solid fa-arrows-alt" /></span>
|
||||||
|
<span>Move selected</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="columns is-multiline">
|
<div class="columns is-multiline">
|
||||||
<div class="column is-12" v-if="items && items.length > 0">
|
<div class="column is-12" v-if="items && items.length > 0">
|
||||||
<div :class="{ 'table-container': table_container }">
|
<div :class="{ 'table-container': table_container }">
|
||||||
|
|
@ -63,6 +83,9 @@
|
||||||
style="min-width: 1300px; table-layout: fixed;">
|
style="min-width: 1300px; table-layout: fixed;">
|
||||||
<thead>
|
<thead>
|
||||||
<tr class="has-text-centered is-unselectable">
|
<tr class="has-text-centered is-unselectable">
|
||||||
|
<th width="5%" v-if="config.app.browser_control_enabled">
|
||||||
|
<input type="checkbox" v-model="masterSelectAll" />
|
||||||
|
</th>
|
||||||
<th width="6%" @click="changeSort('type')">
|
<th width="6%" @click="changeSort('type')">
|
||||||
#
|
#
|
||||||
<span class="icon" v-if="'type' === sort_by">
|
<span class="icon" v-if="'type' === sort_by">
|
||||||
|
|
@ -70,7 +93,7 @@
|
||||||
:class="{ 'fa-sort-up': 'desc' === sort_order, 'fa-sort-down': 'asc' === sort_order }" />
|
:class="{ 'fa-sort-up': 'desc' === sort_order, 'fa-sort-down': 'asc' === sort_order }" />
|
||||||
</span>
|
</span>
|
||||||
</th>
|
</th>
|
||||||
<th width="70%" @click="changeSort('name')">
|
<th width="65%" @click="changeSort('name')">
|
||||||
Name
|
Name
|
||||||
<span class="icon" v-if="'name' === sort_by">
|
<span class="icon" v-if="'name' === sort_by">
|
||||||
<i class="fas"
|
<i class="fas"
|
||||||
|
|
@ -100,6 +123,9 @@
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="item in filteredItems" :key="item.path">
|
<tr v-for="item in filteredItems" :key="item.path">
|
||||||
|
<td class="has-text-centered is-vcentered" v-if="config.app.browser_control_enabled">
|
||||||
|
<input type="checkbox" v-model="selectedElms" :value="item.path" />
|
||||||
|
</td>
|
||||||
<td class="has-text-centered is-vcentered user-hint" v-tooltip="item.name">
|
<td class="has-text-centered is-vcentered user-hint" v-tooltip="item.name">
|
||||||
<span class="icon"><i class="fas fa-2x fa-solid" :class="setIcon(item)" /></span>
|
<span class="icon"><i class="fas fa-2x fa-solid" :class="setIcon(item)" /></span>
|
||||||
</td>
|
</td>
|
||||||
|
|
@ -181,6 +207,7 @@
|
||||||
</Message>
|
</Message>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modal is-active" v-if="model_item">
|
<div class="modal is-active" v-if="model_item">
|
||||||
<div class="modal-background" @click="closeModel"></div>
|
<div class="modal-background" @click="closeModel"></div>
|
||||||
<div class="modal-content is-unbounded-model">
|
<div class="modal-content is-unbounded-model">
|
||||||
|
|
@ -192,6 +219,9 @@
|
||||||
</div>
|
</div>
|
||||||
<button class="modal-close is-large" aria-label="close" @click="closeModel"></button>
|
<button class="modal-close is-large" aria-label="close" @click="closeModel"></button>
|
||||||
</div>
|
</div>
|
||||||
|
<ConfirmDialog v-if="dialog_confirm.visible" :visible="dialog_confirm.visible" :title="dialog_confirm.title"
|
||||||
|
:message="dialog_confirm.message" :options="dialog_confirm.options" @confirm="dialog_confirm.confirm"
|
||||||
|
:html_message="dialog_confirm.html_message" @cancel="dialog_confirm = reset_dialog()" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
@ -205,12 +235,16 @@ const toast = useNotification()
|
||||||
const config = useConfigStore()
|
const config = useConfigStore()
|
||||||
const socket = useSocketStore()
|
const socket = useSocketStore()
|
||||||
const isMobile = useMediaQuery({ maxWidth: 1024 })
|
const isMobile = useMediaQuery({ maxWidth: 1024 })
|
||||||
|
const dialog = useDialog()
|
||||||
|
|
||||||
const bg_enable = useStorage('random_bg', true)
|
const bg_enable = useStorage('random_bg', true)
|
||||||
const bg_opacity = useStorage('random_bg_opacity', 0.95)
|
const bg_opacity = useStorage('random_bg_opacity', 0.95)
|
||||||
const sort_by = useStorage('sort_by', 'name')
|
const sort_by = useStorage('sort_by', 'name')
|
||||||
const sort_order = useStorage('sort_order', 'asc')
|
const sort_order = useStorage('sort_order', 'asc')
|
||||||
|
|
||||||
|
const selectedElms = ref<string[]>([])
|
||||||
|
const masterSelectAll = ref(false)
|
||||||
|
|
||||||
const isLoading = ref<boolean>(false)
|
const isLoading = ref<boolean>(false)
|
||||||
const initialLoad = ref<boolean>(true)
|
const initialLoad = ref<boolean>(true)
|
||||||
const items = ref<FileItem[]>([])
|
const items = ref<FileItem[]>([])
|
||||||
|
|
@ -225,12 +259,31 @@ const table_container = ref<boolean>(false)
|
||||||
const search = ref<string>('')
|
const search = ref<string>('')
|
||||||
const show_filter = ref<boolean>(false)
|
const show_filter = ref<boolean>(false)
|
||||||
|
|
||||||
|
const reset_dialog = () => ({
|
||||||
|
visible: false,
|
||||||
|
title: 'Confirm Action',
|
||||||
|
confirm: (opts: any) => { },
|
||||||
|
message: '',
|
||||||
|
html_message: '',
|
||||||
|
options: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const dialog_confirm = ref(reset_dialog())
|
||||||
|
|
||||||
|
watch(masterSelectAll, v => {
|
||||||
|
if (v) {
|
||||||
|
selectedElms.value = filteredItems.value.map(i => i.path)
|
||||||
|
} else {
|
||||||
|
selectedElms.value = []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
watch(() => config.app.basic_mode, async v => {
|
watch(() => config.app.basic_mode, async v => {
|
||||||
if (!config.isLoaded() || !v) {
|
if (!config.isLoaded() || !v) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await navigateTo('/')
|
await navigateTo('/')
|
||||||
},{ immediate: true })
|
}, { immediate: true })
|
||||||
|
|
||||||
|
|
||||||
const filteredItems = computed<FileItem[]>(() => {
|
const filteredItems = computed<FileItem[]>(() => {
|
||||||
|
|
@ -523,8 +576,14 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('rename' === action) {
|
if ('rename' === action) {
|
||||||
const newName = prompt('Enter new name for the item:', item.name)
|
const { status, value: newName } = await dialog.promptDialog({
|
||||||
if (!newName) {
|
title: 'Rename Item',
|
||||||
|
message: `Enter new name for '${item.name}':`,
|
||||||
|
initial: item.name,
|
||||||
|
confirmText: 'Rename',
|
||||||
|
cancelText: 'Cancel',
|
||||||
|
})
|
||||||
|
if (true !== status) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -533,7 +592,7 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await actionRequest(item, 'rename', { new_name: new_name }, (item, action, data) => {
|
await actionRequest(item, 'rename', { new_name: new_name }, (item, _, data) => {
|
||||||
item.name = data.new_name
|
item.name = data.new_name
|
||||||
item.path = item.path.replace(/[^/]+$/, data.new_name)
|
item.path = item.path.replace(/[^/]+$/, data.new_name)
|
||||||
toast.success(`Renamed '${item.name}'.`)
|
toast.success(`Renamed '${item.name}'.`)
|
||||||
|
|
@ -543,7 +602,15 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
|
||||||
|
|
||||||
if ('delete' === action) {
|
if ('delete' === action) {
|
||||||
const msg = item.is_dir ? `Delete '${item.name}' and all its contents?` : `Delete file '${item.name}'?`
|
const msg = item.is_dir ? `Delete '${item.name}' and all its contents?` : `Delete file '${item.name}'?`
|
||||||
if (false === confirm(msg)) {
|
const { status } = await dialog.confirmDialog({
|
||||||
|
title: 'Delete Confirmation',
|
||||||
|
message: msg,
|
||||||
|
confirmText: 'Delete',
|
||||||
|
cancelText: 'Cancel',
|
||||||
|
confirmColor: 'is-danger',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (true !== status) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -556,8 +623,15 @@ const handleAction = async (action: string, item: FileItem): Promise<void> => {
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('move' === action) {
|
if ('move' === action) {
|
||||||
const newPath = prompt('Enter new path:', item.path.replace(/[^/]+$/, ''))
|
const { status, value: newPath } = await dialog.promptDialog({
|
||||||
if (!newPath) {
|
title: 'Move Item',
|
||||||
|
message: `Enter new path for '${item.name}':`,
|
||||||
|
initial: item.path.replace(/[^/]+$/, ''),
|
||||||
|
confirmText: 'Move',
|
||||||
|
cancelText: 'Cancel',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (true !== status) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -590,13 +664,13 @@ const actionRequest = async (
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await request(`/api/file/action/${encodePath(item.path)}`, {
|
const response = await request(`/api/file/actions`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify([{
|
||||||
path: item.path,
|
path: item.path,
|
||||||
action: action,
|
action: action,
|
||||||
...data
|
...data
|
||||||
}),
|
}]),
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|
@ -605,9 +679,21 @@ const actionRequest = async (
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cb && typeof cb === 'function') {
|
const json = await response.json() as Array<{ path: string, status: boolean, error?: string }>
|
||||||
cb(item, action, data)
|
json.forEach(i => {
|
||||||
}
|
if (i.path !== item.path) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (true !== i.status) {
|
||||||
|
toast.error(`Failed to perform action: ${i.error || 'Unknown error'}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cb && typeof cb === 'function') {
|
||||||
|
cb(item, action, data)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return response
|
return response
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
|
|
@ -615,4 +701,26 @@ const actionRequest = async (
|
||||||
toast.error(`Failed to perform action: ${error.message}`)
|
toast.error(`Failed to perform action: ${error.message}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const confirm_delete = () => {
|
||||||
|
if (selectedElms.value.length < 1) {
|
||||||
|
toast.error('No items selected.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dialog_confirm.value.visible = true
|
||||||
|
dialog_confirm.value.title = 'Delete Confirmation'
|
||||||
|
|
||||||
|
dialog_confirm.value.html_message = `Delete the following items?<ul>` + selectedElms.value.map(p => {
|
||||||
|
const item = items.value.find(i => i.path === p)
|
||||||
|
if (!item) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
const color = item.type === 'dir' ? 'has-text-primary is-bold' : ''
|
||||||
|
|
||||||
|
return `<li><span class="icon"><i class="fa-solid ${setIcon(item)}"></i></span> <span class="${color}">${item.name}</span></li>`
|
||||||
|
}).join('') + `</ul>`
|
||||||
|
|
||||||
|
// dialog_confirm.value.confirm = async () => await deleteSelected()
|
||||||
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue