Merge pull request #402 from arabcoders/dev
Some checks failed
Build Native wrappers / build (amd64, ubuntu-latest) (push) Has been cancelled
Build Native wrappers / build (amd64, windows-latest) (push) Has been cancelled
Build Native wrappers / build (arm64, macos-latest) (push) Has been cancelled
Build Native wrappers / build (arm64, ubuntu-latest) (push) Has been cancelled
Build Native wrappers / build (arm64, windows-latest) (push) Has been cancelled

Enhance file browser API
This commit is contained in:
Abdulmohsen 2025-09-01 19:56:16 +03:00 committed by GitHub
commit 984d47e946
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 746 additions and 301 deletions

View file

@ -26,6 +26,7 @@ class _Entry:
self.size: int = -1 self.size: int = -1
self.mtime: float = -1.0 self.mtime: float = -1.0
self.loaded: bool = False self.loaded: bool = False
self.last_check: float = 0.0
class Archiver(metaclass=ThreadSafe): class Archiver(metaclass=ThreadSafe):
@ -45,7 +46,8 @@ class Archiver(metaclass=ThreadSafe):
self._cache: dict[str, _Entry] = {} self._cache: dict[str, _Entry] = {}
self._locks: dict[str, threading.RLock] = {} self._locks: dict[str, threading.RLock] = {}
self._global_lock = threading.RLock() self._global_lock = threading.RLock()
self._stats_check: bool = False self._stats_check: bool = True
self._stats_ttl: float = 0.2
self._initialized = True self._initialized = True
@classmethod @classmethod
@ -130,7 +132,13 @@ class Archiver(metaclass=ThreadSafe):
if not self._stats_check: if not self._stats_check:
return entry return entry
if self._stats_ttl > 0:
now = time.monotonic()
if (now - (entry.last_check or 0.0)) < self._stats_ttl:
return entry
st: os.stat_result | None = self._stat(key) st: os.stat_result | None = self._stat(key)
entry.last_check = time.monotonic()
if not st: if not st:
self._cache[key] = _Entry() self._cache[key] = _Entry()
@ -148,6 +156,7 @@ class Archiver(metaclass=ThreadSafe):
entry.size = -1 entry.size = -1
entry.mtime = -1 entry.mtime = -1
entry.loaded = True entry.loaded = True
entry.last_check = time.monotonic()
self._cache[key] = entry self._cache[key] = entry
return entry return entry
@ -178,6 +187,7 @@ class Archiver(metaclass=ThreadSafe):
entry.size = st.st_size entry.size = st.st_size
entry.mtime = st.st_mtime entry.mtime = st.st_mtime
entry.loaded = True entry.loaded = True
entry.last_check = time.monotonic()
self._cache[key] = entry self._cache[key] = entry
return entry return entry
@ -284,6 +294,7 @@ class Archiver(metaclass=ThreadSafe):
st: os.stat_result | None = self._stat(key) st: os.stat_result | None = self._stat(key)
if st: if st:
entry.size, entry.mtime = st.st_size, st.st_mtime entry.size, entry.mtime = st.st_size, st.st_mtime
entry.last_check = time.monotonic()
return True return True
@ -353,12 +364,12 @@ class Archiver(metaclass=ThreadSafe):
st: os.stat_result | None = self._stat(key) st: os.stat_result | None = self._stat(key)
if st: if st:
entry.size, entry.mtime = st.st_size, st.st_mtime entry.size, entry.mtime = st.st_size, st.st_mtime
entry.last_check = time.monotonic()
self._cache[key] = entry self._cache[key] = entry
return True return True
# Global configuration
@classmethod @classmethod
def set_skip_read_stat_checks(cls, skip: bool = True) -> None: def set_skip_read_stat_checks(cls, skip: bool = True) -> None:
""" """
@ -375,3 +386,17 @@ class Archiver(metaclass=ThreadSafe):
inst = cls.get_instance() inst = cls.get_instance()
with inst._global_lock: with inst._global_lock:
inst._stats_check = not skip inst._stats_check = not skip
@classmethod
def set_read_stat_ttl(cls, seconds: float = 0.0) -> None:
"""
Set a short TTL to throttle os.stat checks on reads.
Args:
seconds (float): Minimum time between successive stat() calls per file
when checking for external changes. Use 0 to disable throttling.
"""
inst = cls.get_instance()
with inst._global_lock:
inst._stats_ttl = max(0.0, float(seconds))

View file

@ -151,11 +151,7 @@ class Item:
from .Utils import arg_converter from .Utils import arg_converter
try: try:
removed_options: list = [] arg_converter(args=cli, level=True)
arg_converter(args=cli, level=True, removed_options=removed_options)
if len(removed_options) > 0:
LOG.warning("Removed the following options '%s' for '%s'.", ", ".join(removed_options), url)
data["cli"] = cli data["cli"] = cli
except Exception as e: except Exception as e:
msg = f"Failed to parse command options for yt-dlp. {e!s}" msg = f"Failed to parse command options for yt-dlp. {e!s}"

View file

@ -76,18 +76,12 @@ class YTDLPOpts:
if from_user: if from_user:
bad_options: dict[str, str] = {k: v for d in REMOVE_KEYS for k, v in d.items()} bad_options: dict[str, str] = {k: v for d in REMOVE_KEYS for k, v in d.items()}
removed_options: list = []
for key, value in config.items(): for key, value in config.items():
if from_user and key in bad_options: if from_user and key in bad_options:
removed_options.append(bad_options[key])
continue continue
self._item_opts[key] = value self._item_opts[key] = value
if len(removed_options) > 0:
LOG.warning("Removed the following options: '%s'.", ", ".join(removed_options))
return self return self
def preset(self, name: str) -> "YTDLPOpts": def preset(self, name: str) -> "YTDLPOpts":
@ -175,15 +169,7 @@ class YTDLPOpts:
if len(self._item_cli) > 0: if len(self._item_cli) > 0:
try: try:
removed_options: list = [] user_cli: dict = arg_converter(args="\n".join(self._item_cli), level=True)
user_cli: dict = arg_converter(
args="\n".join(self._item_cli),
level=True,
removed_options=removed_options,
)
if len(removed_options) > 0:
LOG.warning("Removed the following options: '%s'.", ", ".join(removed_options))
except Exception as e: except Exception as e:
msg = f"Invalid command options for yt-dlp were given. '{e!s}'." msg = f"Invalid command options for yt-dlp were given. '{e!s}'."
raise ValueError(msg) from e raise ValueError(msg) from e

View file

@ -1,12 +1,9 @@
import logging
from typing import Any from typing import Any
import yt_dlp import yt_dlp
import app.postprocessors # noqa: F401 import app.postprocessors # noqa: F401
LOG: logging.Logger = logging.getLogger(__name__)
class _ArchiveProxy: class _ArchiveProxy:
""" """
@ -26,7 +23,6 @@ class _ArchiveProxy:
from app.library.Archiver import Archiver from app.library.Archiver import Archiver
status: bool = item in Archiver.get_instance().read(self._file, [item]) status: bool = item in Archiver.get_instance().read(self._file, [item])
LOG.debug(f"ArchiveProxy: '{item}' in '{self._file}': {'yes' if status else 'no'}.")
return status return status
except Exception: except Exception:
return False return False
@ -39,7 +35,6 @@ class _ArchiveProxy:
from app.library.Archiver import Archiver from app.library.Archiver import Archiver
status: bool = Archiver.get_instance().add(self._file, [item]) status: bool = Archiver.get_instance().add(self._file, [item])
LOG.debug(f"ArchiveProxy: Added '{item}' to '{self._file}': {'yes' if status else 'no'}.")
return status return status
except Exception: except Exception:
return False return False

View file

@ -135,7 +135,24 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
req_path: str = request.match_info.get("path") req_path: str = request.match_info.get("path")
req_path: str = "/" if not req_path else unquote_plus(req_path) req_path: str = "/" if not req_path else unquote_plus(req_path)
test: Path = Path(config.download_path).joinpath(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 = "/"
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("/")
try:
test.relative_to(root_dir)
except Exception:
return web.json_response(
data={"error": f"path '{req_path}' does not exist."}, status=web.HTTPNotFound.status_code
)
if not test.exists(): if not test.exists():
return web.json_response( return web.json_response(
data={"error": f"path '{req_path}' does not exist."}, status=web.HTTPNotFound.status_code data={"error": f"path '{req_path}' does not exist."}, status=web.HTTPNotFound.status_code
@ -149,8 +166,8 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
try: try:
return web.json_response( return web.json_response(
data={ data={
"path": req_path, "path": rel_for_listing,
"contents": get_files(base_path=Path(config.download_path), dir=req_path), "contents": get_files(base_path=root_dir, dir=rel_for_listing),
}, },
status=web.HTTPOk.status_code, status=web.HTTPOk.status_code,
dumps=encoder.encode, dumps=encoder.encode,
@ -160,8 +177,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 +201,254 @@ 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)
if not rel or rel == ".":
rel = "/"
LOG.info(f"Deleted '{path.relative_to(config.download_path)}'") entry: dict = {"path": rel, "status": ok, "error": error}
except OSError as e:
LOG.exception(e)
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
if "move" == action: if action:
new_path = params.get("new_path") entry["action"] = action
if not new_path:
return web.json_response(data={"error": "New path is required."}, status=web.HTTPBadRequest.status_code)
new_path = Path(config.download_path).joinpath(unquote_plus(new_path)) if extra:
if not new_path.exists() or not new_path.is_dir(): norm_extra: dict = {}
return web.json_response( for k, v in extra.items():
data={"error": f"New path '{new_path}' does not exist or is not a directory."}, if isinstance(v, Path):
status=web.HTTPNotFound.status_code, 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)
# perform each action
for params in actions:
req_path: str = params.get("path")
if not req_path:
record("no_path", ok=False, error="Path is required.", extra={"item": params})
continue
action: str = params.get("action", "").lower()
if not action:
record(req_path, ok=False, error="Action is required.", extra={"item": params})
continue
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():
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, extra={"item": params})
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
if not path.is_relative_to(rootPath):
record(path, ok=False, error="Path outside download root.", action=action)
continue
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.", action=action)
continue
new_path = path.joinpath(*new_dir.split("/"))
try:
new_path = new_path.resolve(strict=False)
except Exception:
record(path, ok=False, error="Invalid directory path.", action=action, extra={"new_dir": new_dir})
continue
root_real = Path(config.download_path).resolve()
if not new_path.is_relative_to(root_real):
record(path, ok=False, error="Destination outside root.", action=action, extra={"new_dir": new_path})
continue
if new_path.exists():
dst = new_path.relative_to(config.download_path)
record(path, ok=False, error="Directory already exists.", action=action, extra={"new_dir": dst})
continue
try:
new_path.mkdir(parents=True, exist_ok=True)
record(path, ok=True, action=action, extra={"new_dir": new_path.relative_to(config.download_path)})
LOG.info(f"Created directory '{new_path.relative_to(config.download_path)}'")
except OSError as e:
LOG.exception(e)
record(path, ok=False, error=str(e), action=action, extra={"item": params})
continue
if "rename" == action:
new_name: str = params.get("new_name")
if not new_name:
record(path, ok=False, error="New name is required for rename action.", action=action)
continue
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:
renamed = path.rename(new_path)
LOG.info(
f"Renamed '{path.relative_to(config.download_path)}' to '{renamed.relative_to(config.download_path)}'"
)
except OSError as e:
LOG.exception(e)
record(path, ok=False, error=str(e), action=action, extra={"item": params})
continue
else:
record(path, ok=True, action=action, extra={"new_path": renamed})
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, extra={"item": params})
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, extra={"item": params})
continue
raw_new: str = unquote_plus(str(new_path)).strip()
target_dir = (
Path(config.download_path)
if not raw_new or raw_new in ("/", ".")
else Path(config.download_path).joinpath(raw_new.lstrip("/"))
) )
new_path = path.joinpath(*new_dir.split("/")) try:
if new_path.exists(): target_dir = target_dir.resolve()
return web.json_response( except Exception:
data={"error": f"Directory '{new_dir}' already exists."}, status=web.HTTPConflict.status_code record(
) path, ok=False, error="Destination path is invalid.", action=action, extra={"new_path": target_dir}
)
continue
try: root_real = Path(config.download_path).resolve()
new_path.mkdir(parents=True, exist_ok=True) if not target_dir.exists() or not target_dir.is_dir():
LOG.info(f"Created directory '{new_path.relative_to(config.download_path)}'") record(
except OSError as e: path, ok=False, error="Destination path is invalid.", action=action, extra={"new_path": target_dir}
LOG.exception(e) )
return web.json_response( continue
data={"error": str(e), "path": str(test)}, status=web.HTTPInternalServerError.status_code
)
return web.Response(status=web.HTTPOk.status_code) if not target_dir.is_relative_to(root_real):
record(
path,
ok=False,
error="Destination outside download root.",
action=action,
extra={"new_path": target_dir},
)
continue
if path.parent == target_dir:
record(path, ok=False, error="Source and destination are the same.", action=action)
continue
try:
dest = target_dir.joinpath(path.name)
path.rename(dest)
except OSError as e:
LOG.exception(e)
record(path, ok=False, error=str(e), action=action, extra={"item": params})
continue
else:
record(path, ok=True, action=action, extra={"new_path": dest})
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")

View file

@ -343,7 +343,7 @@ const importItem = async (): Promise<void> => {
return return
} }
if ((form.filter || form.cli) && !box.confirm('Overwrite the current form fields?', true)) { if ((form.filter || form.cli) && !(await box.confirm('Overwrite the current form fields?', true))) {
return return
} }

View file

@ -56,6 +56,8 @@
</span> </span>
</p> </p>
</div> </div>
<div v-else-if="'confirm' === state.current?.type && (state.current?.opts as ConfirmOptions)?.rawHTML"
class="content" v-html="(state.current?.opts as ConfirmOptions)?.rawHTML" />
</section> </section>
<footer class="modal-card-foot p-4 is-justify-content-flex-end"> <footer class="modal-card-foot p-4 is-justify-content-flex-end">
@ -71,7 +73,8 @@
<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 +100,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 ConfirmOptions, type PromptOptions } from '~/composables/useDialog'
const { state, confirm, cancel } = useDialog() const { state, confirm, cancel } = useDialog()

View file

@ -2,7 +2,6 @@
code { code {
color: var(--bulma-code) !important color: var(--bulma-code) !important
} }
</style> </style>
<template> <template>

View file

@ -588,7 +588,7 @@ const hasDownloaded = computed(() => {
return false return false
}) })
const deleteSelectedItems = () => { const deleteSelectedItems = async () => {
if (selectedElms.value.length < 1) { if (selectedElms.value.length < 1) {
toast.error('No items selected.') toast.error('No items selected.')
return return
@ -597,7 +597,7 @@ const deleteSelectedItems = () => {
if (true === config.app.remove_files) { if (true === config.app.remove_files) {
msg += ' This will remove any associated files if they exists.' msg += ' This will remove any associated files if they exists.'
} }
if (false === box.confirm(msg, config.app.remove_files)) { if (false === (await box.confirm(msg, config.app.remove_files))) {
return return
} }
for (const key in selectedElms.value) { for (const key in selectedElms.value) {
@ -614,9 +614,9 @@ const deleteSelectedItems = () => {
selectedElms.value = [] selectedElms.value = []
} }
const clearCompleted = () => { const clearCompleted = async () => {
let msg = 'Clear all completed downloads?' let msg = 'Clear all completed downloads?'
if (false === box.confirm(msg)) { if (false === (await box.confirm(msg))) {
return return
} }
for (const key in stateStore.history) { for (const key in stateStore.history) {
@ -626,8 +626,8 @@ const clearCompleted = () => {
} }
} }
const clearIncomplete = () => { const clearIncomplete = async () => {
if (false === box.confirm('Clear all in-complete downloads?')) { if (false === (await box.confirm('Clear all in-complete downloads?'))) {
return return
} }
for (const key in stateStore.history) { for (const key in stateStore.history) {
@ -706,8 +706,8 @@ const setStatus = (item: StoreItem) => {
return item.status return item.status
} }
const retryIncomplete = () => { const retryIncomplete = async () => {
if (false === box.confirm('Retry all incomplete downloads?')) { if (false === (await box.confirm('Retry all incomplete downloads?'))) {
return false return false
} }
for (const key in stateStore.history) { for (const key in stateStore.history) {
@ -746,12 +746,12 @@ const archiveItem = async (item: StoreItem, opts = {}) => {
socket.emit('item_delete', { id: item._id, remove_file: false }) socket.emit('item_delete', { id: item._id, remove_file: false })
} }
const removeItem = (item: StoreItem) => { const removeItem = async (item: StoreItem) => {
let msg = `${config.app.remove_files ? 'Remove' : 'Clear'} '${item.title || item.id || item.url || '??'}'?` let msg = `${config.app.remove_files ? 'Remove' : 'Clear'} '${item.title || item.id || item.url || '??'}'?`
if (item.status === 'finished' && config.app.remove_files) { if (item.status === 'finished' && config.app.remove_files) {
msg += ' This will remove any associated files if they exists.' msg += ' This will remove any associated files if they exists.'
} }
if (false === box.confirm(msg, Boolean(item.filename && config.app.remove_files))) { if (false === (await box.confirm(msg, Boolean(item.filename && config.app.remove_files)))) {
return false return false
} }
socket.emit('item_delete', { socket.emit('item_delete', {

View file

@ -373,7 +373,7 @@ const importItem = async () => {
} }
if (form.name || form.request?.url) { if (form.name || form.request?.url) {
if (false === box.confirm('Overwrite the current form fields?', true)) { if (false === (await box.confirm('Overwrite the current form fields?', true))) {
return return
} }
} }

View file

@ -240,7 +240,7 @@
v-rtime="item.datetime" /> v-rtime="item.datetime" />
</div> </div>
<div class="column is-half-mobile has-text-centered is-text-overflow is-unselectable" <div class="column is-half-mobile has-text-centered is-text-overflow is-unselectable"
v-if="item.downloaded_bytes"> v-if="item.downloaded_bytes" v-tooltip="`Saving to: ${makePath(item)}`">
{{ formatBytes(item.downloaded_bytes) }} {{ formatBytes(item.downloaded_bytes) }}
</div> </div>
@ -507,16 +507,16 @@ const updateProgress = (item: StoreItem): string => {
return string return string
} }
const confirmCancel = (item: StoreItem) => { const confirmCancel = async (item: StoreItem) => {
if (true !== box.confirm(`Cancel '${item.title}'?`)) { if (true !== (await box.confirm(`Cancel '${item.title}'?`))) {
return false return false
} }
cancelItems(item._id) cancelItems(item._id)
return true return true
} }
const cancelSelected = () => { const cancelSelected = async () => {
if (true !== box.confirm(`Cancel '${selectedElms.value.length}' selected items?`)) { if (true !== (await box.confirm(`Cancel '${selectedElms.value.length}' selected items?`))) {
return false return false
} }
cancelItems(selectedElms.value) cancelItems(selectedElms.value)
@ -543,7 +543,7 @@ const cancelItems = (item: string | string[]) => {
const startItem = (item: StoreItem) => socket.emit('item_start', item._id) const startItem = (item: StoreItem) => socket.emit('item_start', item._id)
const pauseItem = (item: StoreItem) => socket.emit('item_pause', item._id) const pauseItem = (item: StoreItem) => socket.emit('item_pause', item._id)
const startItems = () => { const startItems = async () => {
if (1 > selectedElms.value.length) { if (1 > selectedElms.value.length) {
return return
} }
@ -559,13 +559,13 @@ const startItems = () => {
toast.error('No eligible items to start.') toast.error('No eligible items to start.')
return return
} }
if (true !== box.confirm(`Start '${filtered.length}' selected items?`)) { if (true !== (await box.confirm(`Start '${filtered.length}' selected items?`))) {
return false return false
} }
filtered.forEach(id => socket.emit('item_start', id)) filtered.forEach(id => socket.emit('item_start', id))
} }
const pauseSelected = () => { const pauseSelected = async () => {
if (1 > selectedElms.value.length) { if (1 > selectedElms.value.length) {
return return
} }
@ -581,7 +581,7 @@ const pauseSelected = () => {
toast.error('No eligible items to pause.') toast.error('No eligible items to pause.')
return return
} }
if (true !== box.confirm(`Pause '${filtered.length}' selected items?`)) { if (true !== (await box.confirm(`Pause '${filtered.length}' selected items?`))) {
return false return false
} }
filtered.forEach(id => socket.emit('item_pause', id)) filtered.forEach(id => socket.emit('item_pause', id))
@ -598,4 +598,15 @@ watch(embed_url, v => {
} }
document.querySelector('body')?.setAttribute('style', `opacity: ${v ? 1 : bg_opacity.value}`) document.querySelector('body')?.setAttribute('style', `opacity: ${v ? 1 : bg_opacity.value}`)
}) })
const makePath = (item: StoreItem) => {
const parts = [
eTrim(item.download_dir, '/').replace(config.app.download_path, ''),
]
if (item?.filename) {
parts.push(eTrim(item.filename, '/'))
}
return '/' + sTrim(parts.filter(p => !!p).map(p => p.replace(/\\/g, '/').replace(/\/+/g, '/')).join('/'), '/')
}
</script> </script>

View file

@ -409,7 +409,7 @@ const importItem = async (): Promise<void> => {
} }
if (form.url || form.timer) { if (form.url || form.timer) {
if (false === box.confirm('Overwrite the current form fields?', true)) { if (false === (await box.confirm('Overwrite the current form fields?', true))) {
return return
} }
} }

View file

@ -1,21 +1,48 @@
import { useStorage } from '@vueuse/core' import { useStorage } from '@vueuse/core'
import { useDialog } from './useDialog'
const dialog = useDialog()
const reduceConfirm = useStorage<boolean>('reduce_confirm', false) const reduceConfirm = useStorage<boolean>('reduce_confirm', false)
function confirm(msg: string, force: boolean = false): boolean { const confirm = async (msg: string, force: boolean = false) => {
if (false === force && true === reduceConfirm.value) { if (false === force && true === reduceConfirm.value) {
return true return true
} }
return window.confirm(msg) const { status } = await dialog.confirmDialog({
title: 'Please Confirm',
message: msg,
cancelText: 'Cancel',
confirmText: 'OK',
})
return status
} }
function alert(msg: string): boolean { const alert = async (msg: string) => {
return window.confirm(msg) const { status } = await dialog.alertDialog({
title: 'Alert',
message: msg,
confirmText: 'OK',
})
return status
} }
function prompt(msg: string, defaultValue: string = ''): string | null { const prompt = async (msg: string, defaultValue: string = '') => {
return window.prompt(msg, defaultValue) const { status, value } = await dialog.promptDialog({
title: 'Input Required',
message: msg,
initial: defaultValue,
cancelText: 'Cancel',
confirmText: 'OK',
})
if (status) {
return value
}
return null
} }
export default function useConfirm() { export default function useConfirm() {

View file

@ -1,127 +1,135 @@
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
/**
* Raw HTML content to include in the dialog message.
*/
rawHTML?: 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>,
} }
} }

View file

@ -27,22 +27,24 @@
</div> </div>
<div class="control"> <div class="control">
<button class="button is-danger is-light" @click="toggleFilter" v-tooltip.bottom="'Filter content'"> <button class="button is-danger is-light" @click="toggleFilter">
<span class="icon"><i class="fas fa-filter" /></span> <span class="icon"><i class="fas fa-filter" /></span>
<span v-if="!isMobile">Filter</span>
</button> </button>
</div> </div>
<p class="control"> <p class="control">
<button class="button is-info is-light" @click="createDirectory(path)" <button class="button is-info is-light" @click="createDirectory(path)"
:class="{ 'is-loading': isLoading }" :disabled="!socket.isConnected || isLoading" v-if="config.app.browser_control_enabled">
v-tooltip.bottom="'Create new directory'" v-if="config.app.browser_control_enabled">
<span class="icon"><i class="fas fa-folder-plus" /></span> <span class="icon"><i class="fas fa-folder-plus" /></span>
<span v-if="!isMobile">New Folder</span>
</button> </button>
</p> </p>
<p class="control"> <p class="control">
<button class="button is-info" @click="reloadContent(path, true)" :class="{ 'is-loading': isLoading }" <button class="button is-info" @click="reloadContent(path, true)" :class="{ 'is-loading': isLoading }"
:disabled="!socket.isConnected || isLoading"> :disabled="!socket.isConnected || isLoading">
<span class="icon"><i class="fas fa-refresh" /></span> <span class="icon"><i class="fas fa-refresh" /></span>
<span v-if="!isMobile">Reload</span>
</button> </button>
</p> </p>
</div> </div>
@ -53,6 +55,27 @@
</div> </div>
</div> </div>
<div class="columns is-multiline" v-if="config.app.browser_control_enabled">
<div class="column is-half-mobile">
<button type="button" class="button is-fullwidth is-danger" @click="deleteSelected"
:disabled="selectedElms.length < 1 || isLoading || items.length < 1">
<span class="icon-text is-block">
<span class="icon"><i class="fa-solid fa-trash-can" /></span>
<span>Delete {{ selectedElms.length > 0 ? selectedElms.length : '' }} items</span>
</span>
</button>
</div>
<div class="column is-half-mobile">
<button type="button" class="button is-fullwidth is-link" @click="moveSelected"
:disabled="selectedElms.length < 1 || isLoading || items.length < 1">
<span class="icon-text is-block">
<span class="icon"><i class="fa-solid fa-arrows-alt" /></span>
<span>Move {{ selectedElms.length > 0 ? selectedElms.length : '' }} items</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 }">
@ -60,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">
@ -67,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"
@ -97,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>
@ -178,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">
@ -189,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>
@ -201,12 +234,17 @@ const route = useRoute()
const toast = useNotification() const toast = useNotification()
const config = useConfigStore() const config = useConfigStore()
const socket = useSocketStore() const socket = useSocketStore()
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[]>([])
@ -221,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[]>(() => {
@ -360,6 +417,10 @@ const reloadContent = async (dir: string = '/', fromMounted: boolean = false): P
} }
items.value = [] items.value = []
search.value = ''
selectedElms.value = []
show_filter.value = false
masterSelectAll.value = false
const data = await response.json() as FileBrowserResponse const data = await response.json() as FileBrowserResponse
@ -497,8 +558,15 @@ const createDirectory = async (dir: string): Promise<void> => {
return return
} }
const newDir = prompt('Enter new directory name:', '') const { status, value: newDir } = await dialog.promptDialog({
if (!newDir) { title: 'Create New Directory',
message: `Enter name for new directory in '${dir || '/'}':`,
initial: '',
confirmText: 'Create',
cancelText: 'Cancel',
})
if (true !== status || !newDir) {
return return
} }
@ -507,7 +575,7 @@ const createDirectory = async (dir: string): Promise<void> => {
return return
} }
await actionRequest({ path: dir } as FileItem, 'directory', { new_dir: new_dir }, (item, action, data) => { await actionRequest({ path: dir || '/' } as FileItem, 'directory', { new_dir: new_dir }, (item, action, data) => {
reloadContent(path.value, true) reloadContent(path.value, true)
toast.success(`Successfully created '${new_dir}'.`) toast.success(`Successfully created '${new_dir}'.`)
}) })
@ -519,8 +587,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
} }
@ -529,7 +603,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}'.`)
@ -539,7 +613,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
} }
@ -552,12 +634,19 @@ 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
} }
let new_path = sTrim(newPath, '/') let new_path = sTrim(newPath, '/') || '/'
if (!new_path || new_path === item.path) { if (!new_path || new_path === item.path) {
return return
} }
@ -586,13 +675,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) {
@ -601,9 +690,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) {
@ -611,4 +712,136 @@ const actionRequest = async (
toast.error(`Failed to perform action: ${error.message}`) 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 () => {
if (selectedElms.value.length < 1) {
toast.error('No items selected.')
return
}
const rawHTML = `<ul>` + selectedElms.value.map(p => {
const item = items.value.find(i => i.path === p)
if (!item) {
return ''
}
const color = 'dir' === item.type ? 'has-text-danger is-bold' : ''
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?`,
rawHTML: rawHTML,
confirmText: 'Delete',
cancelText: 'Cancel',
confirmColor: 'is-danger',
})
if (true !== status) {
selectedElms.value = []
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}'.`)
})
}
const moveSelected = async () => {
if (selectedElms.value.length < 1) {
toast.error('No items selected.')
return
}
const { status, value: newPath } = await dialog.promptDialog({
title: 'Move Items',
message: `Enter new path for selected items:`,
initial: path.value || '/',
confirmText: 'Move',
confirmColor: 'is-danger',
cancelText: 'Cancel',
})
if (true !== status || !newPath || newPath === path.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, '/')}'.`)
})
}
</script> </script>

View file

@ -13,12 +13,14 @@
<p class="control"> <p class="control">
<button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm;"> <button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm;">
<span class="icon"><i class="fas fa-add" /></span> <span class="icon"><i class="fas fa-add" /></span>
<span v-if="!isMobile">New Condition</span>
</button> </button>
</p> </p>
<p class="control"> <p class="control">
<button class="button is-info" @click="reloadContent(false)" :class="{ 'is-loading': isLoading }" <button class="button is-info" @click="reloadContent(false)" :class="{ 'is-loading': isLoading }"
:disabled="!socket.isConnected || isLoading" v-if="items && items.length > 0"> :disabled="!socket.isConnected || isLoading" v-if="items && items.length > 0">
<span class="icon"><i class="fas fa-refresh" /></span> <span class="icon"><i class="fas fa-refresh" /></span>
<span v-if="!isMobile">Reload</span>
</button> </button>
</p> </p>
</div> </div>
@ -121,6 +123,7 @@ const toast = useNotification()
const config = useConfigStore() const config = useConfigStore()
const socket = useSocketStore() const socket = useSocketStore()
const box = useConfirm() const box = useConfirm()
const isMobile = useMediaQuery({ maxWidth: 1024 })
const items = ref<ConditionItem[]>([]) const items = ref<ConditionItem[]>([])
const item = ref<Partial<ConditionItem>>({}) const item = ref<Partial<ConditionItem>>({})
@ -219,7 +222,7 @@ const updateItems = async (newItems: ConditionItem[]): Promise<boolean> => {
} }
const deleteItem = async (cond: ConditionItem): Promise<void> => { const deleteItem = async (cond: ConditionItem): Promise<void> => {
if (!box.confirm(`Delete '${cond.name}'?`, true)) { if (true !== (await box.confirm(`Delete '${cond.name}'?`, true))) {
return return
} }

View file

@ -46,9 +46,9 @@
<button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom" <button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom"
@click="() => changeDisplay()"> @click="() => changeDisplay()">
<span class="icon"><i class="fa-solid" <span class="icon"><i class="fa-solid"
:class="{ 'fa-table': display_style === 'cards', 'fa-table-list': display_style === 'list' }" /></span> :class="{ 'fa-table': display_style !== 'list', 'fa-table-list': display_style === 'list' }" /></span>
<span v-if="!isMobile"> <span v-if="!isMobile">
{{ display_style === 'cards' ? 'Cards' : 'List' }} {{ display_style === 'list' ? 'List' : 'Grid' }}
</span> </span>
</button> </button>
</p> </p>
@ -123,8 +123,9 @@ const stateStore = useStateStore()
const socket = useSocketStore() const socket = useSocketStore()
const bg_enable = useStorage<boolean>('random_bg', true) const bg_enable = useStorage<boolean>('random_bg', true)
const bg_opacity = useStorage<number>('random_bg_opacity', 0.95) const bg_opacity = useStorage<number>('random_bg_opacity', 0.95)
const display_style = useStorage<string>('display_style', 'cards') const display_style = useStorage<string>('display_style', 'grid')
const show_thumbnail = useStorage<boolean>('show_thumbnail', true) const show_thumbnail = useStorage<boolean>('show_thumbnail', true)
const isMobile = useMediaQuery({ maxWidth: 1024 })
const info_view = ref({ const info_view = ref({
url: '', url: '',
@ -143,7 +144,6 @@ const dialog_confirm = ref({
options: [], options: [],
}) })
const isMobile = useMediaQuery({ maxWidth: 1024 })
watch(toggleFilter, () => { watch(toggleFilter, () => {
if (!toggleFilter.value) { if (!toggleFilter.value) {
@ -217,7 +217,7 @@ watch(() => info_view.value.url, v => {
document.querySelector('body')?.setAttribute("style", `opacity: ${v ? 1 : bg_opacity.value}`) document.querySelector('body')?.setAttribute("style", `opacity: ${v ? 1 : bg_opacity.value}`)
}) })
const changeDisplay = () => display_style.value = display_style.value === 'cards' ? 'list' : 'cards' const changeDisplay = () => display_style.value = display_style.value === 'grid' ? 'list' : 'grid'
const toNewDownload = async (item: item_request | Partial<StoreItem>) => { const toNewDownload = async (item: item_request | Partial<StoreItem>) => {
if (!item) { if (!item) {

View file

@ -14,19 +14,25 @@
<button class="button is-primary" @click="resetForm(false); toggleForm = true" <button class="button is-primary" @click="resetForm(false); toggleForm = true"
v-tooltip="'Add new notification target.'"> v-tooltip="'Add new notification target.'">
<span class="icon"><i class="fas fa-add"></i></span> <span class="icon"><i class="fas fa-add"></i></span>
<span v-if="!isMobile">New Notification</span>
</button> </button>
</p> </p>
<p class="control" v-if="notifications.length > 0"> <p class="control" v-if="notifications.length > 0">
<button class="button is-warning" @click="sendTest" v-tooltip="'Send test notification.'" <button class="button is-warning" @click="sendTest" v-tooltip="'Send test notification.'"
:class="{ 'is-loading': isLoading }" :disabled="!socket.isConnected || isLoading"> :class="{ 'is-loading': isLoading }" :disabled="!socket.isConnected || isLoading">
<span class="icon"><i class="fas fa-paper-plane"></i></span> <span class="icon"><i class="fas fa-paper-plane"></i></span>
<span v-if="!isMobile">Send Test</span>
</button> </button>
</p> </p>
<p class="control" v-if="notifications.length > 0"> <p class="control" v-if="notifications.length > 0">
<button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom" <button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom"
@click="() => display_style = display_style === 'cards' ? 'list' : 'cards'"> @click="() => display_style = display_style === 'list' ? 'grid' : 'list'">
<span class="icon"><i class="fa-solid" <span class="icon">
:class="{ 'fa-table': display_style === 'cards', 'fa-table-list': display_style === 'list' }" /></span> <i class="fa-solid"
:class="{ 'fa-table': display_style !== 'list', 'fa-table-list': display_style === 'list' }" /></span>
<span v-if="!isMobile">
{{ display_style === 'list' ? 'List' : 'Grid' }}
</span>
</button> </button>
</p> </p>
@ -203,6 +209,7 @@ const config = useConfigStore()
const socket = useSocketStore() const socket = useSocketStore()
const box = useConfirm() const box = useConfirm()
const display_style = useStorage<string>("tasks_display_style", "cards") const display_style = useStorage<string>("tasks_display_style", "cards")
const isMobile = useMediaQuery({ maxWidth: 1024 })
const allowedEvents = ref<string[]>([]) const allowedEvents = ref<string[]>([])
const notifications = ref<notification[]>([]) const notifications = ref<notification[]>([])
@ -305,7 +312,7 @@ const updateData = async (items: notification[]) => {
} }
const deleteItem = async (item: notification) => { const deleteItem = async (item: notification) => {
if (true !== box.confirm(`Delete '${item.name}'?`)) { if (true !== (await box.confirm(`Delete '${item.name}'?`))) {
return return
} }
@ -366,7 +373,7 @@ const join_events = (events: string[]) =>
!events || events.length < 1 ? 'ALL' : events.map(e => ucFirst(e)).join(', ') !events || events.length < 1 ? 'ALL' : events.map(e => ucFirst(e)).join(', ')
const sendTest = async () => { const sendTest = async () => {
if (true !== box.confirm('Send test notification?')) { if (true !== (await box.confirm('Send test notification?'))) {
return return
} }

View file

@ -14,20 +14,26 @@
<button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm;" <button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm;"
v-tooltip.bottom="'Toggle add form'"> v-tooltip.bottom="'Toggle add form'">
<span class="icon"><i class="fas fa-add" /></span> <span class="icon"><i class="fas fa-add" /></span>
<span v-if="!isMobile">New Preset</span>
</button> </button>
</p> </p>
<p class="control"> <p class="control">
<button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom" <button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom"
@click="() => display_style = display_style === 'cards' ? 'list' : 'cards'"> @click="() => display_style = display_style === 'list' ? 'grid' : 'list'">
<span class="icon"><i class="fa-solid" <span class="icon">
:class="{ 'fa-table': display_style === 'cards', 'fa-table-list': display_style === 'list' }" /></span> <i class="fa-solid"
:class="{ 'fa-table': display_style !== 'list', 'fa-table-list': display_style === 'list' }" /></span>
<span v-if="!isMobile">
{{ display_style === 'list' ? 'List' : 'Grid' }}
</span>
</button> </button>
</p> </p>
<p class="control"> <p class="control">
<button class="button is-info" @click="reloadContent()" :class="{ 'is-loading': isLoading }" <button class="button is-info" @click="reloadContent()" :class="{ 'is-loading': isLoading }"
:disabled="!socket.isConnected || isLoading" v-if="presets && presets.length > 0"> :disabled="!socket.isConnected || isLoading" v-if="presets && presets.length > 0">
<span class="icon"><i class="fas fa-refresh" /></span> <span class="icon"><i class="fas fa-refresh" /></span>
<span v-if="!isMobile">Reload</span>
</button> </button>
</p> </p>
</div> </div>
@ -214,6 +220,7 @@ const socket = useSocketStore()
const box = useConfirm() const box = useConfirm()
const display_style = useStorage<string>('preset_display_style', 'cards') const display_style = useStorage<string>('preset_display_style', 'cards')
const isMobile = useMediaQuery({ maxWidth: 1024 })
const presets = ref<Preset[]>([]) const presets = ref<Preset[]>([])
const preset = ref<Partial<Preset>>({}) const preset = ref<Partial<Preset>>({})
@ -304,7 +311,7 @@ const updatePresets = async (items: Preset[]): Promise<boolean | undefined> => {
} }
const deleteItem = async (item: Preset) => { const deleteItem = async (item: Preset) => {
if (true !== box.confirm(`Delete preset '${item.name}'?`, true)) { if (true !== (await box.confirm(`Delete preset '${item.name}'?`, true))) {
return return
} }

View file

@ -20,6 +20,7 @@
<button class="button is-danger is-light" v-tooltip.bottom="'Filter'" <button class="button is-danger is-light" v-tooltip.bottom="'Filter'"
@click="toggleFilter = !toggleFilter"> @click="toggleFilter = !toggleFilter">
<span class="icon"><i class="fas fa-filter" /></span> <span class="icon"><i class="fas fa-filter" /></span>
<span v-if="!isMobile">Filter</span>
</button> </button>
</p> </p>
@ -27,14 +28,19 @@
<button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm" <button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm"
v-tooltip.bottom="'Toggle Add form'"> v-tooltip.bottom="'Toggle Add form'">
<span class="icon"><i class="fas fa-add" /></span> <span class="icon"><i class="fas fa-add" /></span>
<span v-if="!isMobile">New Task</span>
</button> </button>
</p> </p>
<p class="control"> <p class="control">
<button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom" <button v-tooltip.bottom="'Change display style'" class="button has-tooltip-bottom"
@click="() => display_style = display_style === 'cards' ? 'list' : 'cards'"> @click="() => display_style = display_style === 'list' ? 'grid' : 'list'">
<span class="icon"><i class="fa-solid" <span class="icon">
:class="{ 'fa-table': display_style === 'cards', 'fa-table-list': display_style === 'list' }" /></span> <i class="fa-solid"
:class="{ 'fa-table': display_style !== 'list', 'fa-table-list': display_style === 'list' }" /></span>
<span v-if="!isMobile">
{{ display_style === 'list' ? 'List' : 'Grid' }}
</span>
</button> </button>
</p> </p>
@ -42,6 +48,7 @@
<button class="button is-info" @click="reloadContent()" :class="{ 'is-loading': isLoading }" <button class="button is-info" @click="reloadContent()" :class="{ 'is-loading': isLoading }"
:disabled="!socket.isConnected || isLoading" v-if="tasks && tasks.length > 0"> :disabled="!socket.isConnected || isLoading" v-if="tasks && tasks.length > 0">
<span class="icon"><i class="fas fa-refresh" /></span> <span class="icon"><i class="fas fa-refresh" /></span>
<span v-if="!isMobile">Reload</span>
</button> </button>
</p> </p>
</div> </div>
@ -382,6 +389,7 @@ const config = useConfigStore()
const socket = useSocketStore() const socket = useSocketStore()
const { confirmDialog: cDialog } = useDialog() const { confirmDialog: cDialog } = useDialog()
const display_style = useStorage<string>("tasks_display_style", "cards") const display_style = useStorage<string>("tasks_display_style", "cards")
const isMobile = useMediaQuery({ maxWidth: 1024 })
const tasks = ref<Array<task_item>>([]) const tasks = ref<Array<task_item>>([])
const task = ref<task_item | Object>({}) const task = ref<task_item | Object>({})
@ -571,7 +579,7 @@ const deleteSelected = async () => {
} }
const deleteItem = async (item: task_item) => { const deleteItem = async (item: task_item) => {
if (true !== box.confirm(`Delete '${item.name}' task?`, true)) { if (true !== (await box.confirm(`Delete '${item.name}' task?`, true))) {
return return
} }
@ -688,7 +696,7 @@ const runSelected = async () => {
} }
const runNow = async (item: task_item, mass: boolean = false) => { const runNow = async (item: task_item, mass: boolean = false) => {
if (!mass && true !== box.confirm(`Run '${item.name}' now? it will also run at the scheduled time.`)) { if (!mass && true !== (await box.confirm(`Run '${item.name}' now? it will also run at the scheduled time.`))) {
return return
} }