Added file browser actions

This commit is contained in:
arabcoders 2025-07-01 18:05:27 +03:00
parent 1d6f810453
commit 31aa15efba
6 changed files with 336 additions and 18 deletions

View file

@ -307,11 +307,12 @@ Certain configuration values can be set via environment variables, using the `-e
| YTP_PIP_PACKAGES | A space separated list of pip packages to install | `empty string` |
| YTP_PIP_IGNORE_UPDATES | Do not update the custom pip packages | `false` |
| YTP_BASIC_MODE | Whether to run WebUI in basic mode | `false` |
| YTP_PICTURES_BACKENDS | A comma separated list of pictures urls to use. | `empty string` |
| YTP_PICTURES_BACKENDS | A comma separated list of pictures urls to use | `empty string` |
| YTP_BROWSER_ENABLED | Whether to enable the file browser | `false` |
| YTP_BROWSER_CONTROL_ENABLED | Whether to enable the file browser actions | `false` |
| YTP_YTDLP_AUTO_UPDATE | Whether to enable the auto update for yt-dlp | `true` |
| YTP_BASE_PATH | Set this if you are serving YTPTube from sub-folder | `/` |
| YTP_PREVENT_LIVE_PREMIERE | Prevents the initial youtube premiere stream from being downloaded | `false` |
| YTP_TASKS_HANDLER_TIMER | The cron expression for the tasks handler timer. | `15 */1 * * *` |
| YTP_PLAYLIST_ITEMS_CONCURRENCY | The number of playlist items be to processed at same time. | `1` |
| YTP_TASKS_HANDLER_TIMER | The cron expression for the tasks handler timer | `15 */1 * * *` |
| YTP_PLAYLIST_ITEMS_CONCURRENCY | The number of playlist items be to processed at same time | `1` |

View file

@ -157,6 +157,9 @@ class Config:
browser_enabled: bool = False
"Enable file browser access."
browser_control_enabled: bool = False
"Enable file browser control access."
ytdlp_auto_update: bool = True
"""Enable in-place auto update of yt-dlp package."""
@ -227,6 +230,7 @@ class Config:
"file_logging",
"console_enabled",
"browser_enabled",
"browser_control_enabled",
"ytdlp_auto_update",
"prevent_premiere_live",
)
@ -246,6 +250,7 @@ class Config:
"sentry_dsn",
"console_enabled",
"browser_enabled",
"browser_control_enabled",
"ytdlp_cli",
"file_logging",
"base_path",

View file

@ -9,7 +9,7 @@ from app.library.config import Config
from app.library.encoder import Encoder
from app.library.ffprobe import ffprobe
from app.library.router import route
from app.library.Utils import get_file, get_file_sidecar, get_files, get_mime_type
from app.library.Utils import delete_dir, get_file, get_file_sidecar, get_files, get_mime_type
LOG: logging.Logger = logging.getLogger(__name__)
@ -155,3 +155,157 @@ async def file_browser(request: Request, config: Config, encoder: Encoder) -> Re
except OSError as e:
LOG.exception(e)
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
@route("POST", "api/file/action/{path:.*}", "browser.actions")
async def path_action(request: Request, config: Config) -> Response:
"""
Browser actions.
Args:
request (Request): The request object.
config (Config): The configuration object.
Returns:
Response: The response object.
"""
if not config.browser_enabled:
return web.json_response(data={"error": "File browser is disabled."}, status=web.HTTPForbidden.status_code)
if not config.browser_control_enabled:
return web.json_response(
data={"error": "File browser controls is disabled."}, status=web.HTTPForbidden.status_code
)
rootPath: Path = Path(config.download_path)
try:
params = await request.json()
if not params or not isinstance(params, dict):
return web.json_response(data={"error": "Invalid parameters."}, status=web.HTTPBadRequest.status_code)
except Exception as e:
LOG.exception(e)
return web.json_response(data={"error": "Invalid JSON."}, status=web.HTTPBadRequest.status_code)
action = params.get("action").lower()
if not action:
return web.json_response(data={"error": "Action is required."}, status=web.HTTPBadRequest.status_code)
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(
data={"error": f"File {status}: '{test}' does not exist."}, status=web.HTTPNotFound.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,
)
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,
)
if "rename" == action:
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(
data={"error": f"File '{new_name}' already exists."}, status=web.HTTPConflict.status_code
)
try:
path.rename(new_path)
LOG.info(
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:
try:
if not path.exists():
return web.json_response(
data={"error": f"Path '{path}' does not exist."}, status=web.HTTPNotFound.status_code
)
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)
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
if "move" == action:
new_path = params.get("new_path")
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 not new_path.exists() or not new_path.is_dir():
return web.json_response(
data={"error": f"New path '{new_path}' does not exist or is not a directory."},
status=web.HTTPNotFound.status_code,
)
try:
path.rename(new_path.joinpath(path.name))
except OSError as e:
LOG.exception(e)
return web.json_response(data={"error": str(e)}, status=web.HTTPInternalServerError.status_code)
if "directory" == action:
new_dir = params.get("new_dir").lstrip("/").strip()
if not new_dir:
return web.json_response(
data={"error": "New directory name is required."}, status=web.HTTPBadRequest.status_code
)
new_path = path.joinpath(*new_dir.split("/"))
if new_path.exists():
return web.json_response(
data={"error": f"Directory '{new_dir}' already exists."}, status=web.HTTPConflict.status_code
)
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)
return web.json_response(
data={"error": str(e), "path": str(test)}, status=web.HTTPInternalServerError.status_code
)
return web.Response(status=web.HTTPOk.status_code)

View file

@ -26,6 +26,8 @@ type AppConfig = {
console_enabled: boolean
/** Indicates if the file browser is enabled */
browser_enabled: boolean
/** Indicates if the file browser control is enabled */
browser_control_enabled: boolean
/** Command options for yt-dlp */
ytdlp_cli: string
/** Indicates if file logging is enabled */

View file

@ -32,6 +32,13 @@
</button>
</div>
<p class="control">
<button class="button is-info is-light" @click="createDirectory(path)"
:class="{ 'is-loading': isLoading }" :disabled="!socket.isConnected || isLoading"
v-tooltip.bottom="'Create new directory'" v-if="config.app.browser_control_enabled">
<span class="icon"><i class="fas fa-folder-plus" /></span>
</button>
</p>
<p class="control">
<button class="button is-info" @click="reloadContent(path, true)" :class="{ 'is-loading': isLoading }"
:disabled="!socket.isConnected || isLoading">
@ -48,12 +55,12 @@
<div class="columns is-multiline">
<div class="column is-12" v-if="items && items.length > 0">
<div class="table-container is-responsive">
<div :class="{ 'table-container': table_container }">
<table class="table is-striped is-hoverable is-fullwidth is-bordered"
style="min-width: 1300px; table-layout: fixed;">
<thead>
<tr class="has-text-centered is-unselectable">
<th width="5%" @click="changeSort('type')">
<th width="6%" @click="changeSort('type')">
#
<span class="icon" v-if="'type' === sort_by">
<i class="fas"
@ -83,6 +90,9 @@
:class="{ 'fa-sort-up': 'desc' === sort_order, 'fa-sort-down': 'asc' === sort_order }" />
</span>
</th>
<th width="15%" v-if="config.app.browser_control_enabled">
Actions
</th>
</tr>
</thead>
<tbody>
@ -112,14 +122,46 @@
</div>
</div>
</td>
<td class="has-text-centered is-text-overflow is-unselectable">
<td class="has-text-centered is-text-overflow is-unselectable is-vcentered">
{{ 'file' === item.type ? formatBytes(item.size) : ucFirst(item.type) }}
</td>
<td class="has-text-centered is-text-overflow is-unselectable">
<td class="has-text-centered is-text-overflow is-unselectable is-vcentered">
<span :data-datetime="item.mtime" v-tooltip="moment(item.mtime).format('MMMM Do YYYY, h:mm:ss a')">
{{ moment(item.mtime).fromNow() }}
</span>
</td>
<td class="is-vcentered" v-if="config.app.browser_control_enabled">
<Dropdown icons="fa-solid fa-cogs" @open_state="s => table_container = !s" label="Actions">
<template v-if="'file' === item.type">
<a :href="makeDownload({}, { filename: item.path, folder: '' })"
:download="item.name.split('/').reverse()[0]" class="dropdown-item">
<span class="icon"><i class="fa-solid fa-download" /></span>
<span>Download</span>
</a>
<hr class="dropdown-divider" />
</template>
<NuxtLink class="dropdown-item" @click="handleAction('rename', item)">
<span class="icon"><i class="fa-solid fa-edit" /></span>
<span>Rename</span>
</NuxtLink>
<hr class="dropdown-divider" />
<NuxtLink class="dropdown-item" @click="handleAction('delete', item)">
<span class="icon has-text-danger"><i class="fa-solid fa-trash" /></span>
<span>Delete</span>
</NuxtLink>
<hr class="dropdown-divider" />
<NuxtLink class="dropdown-item" @click="handleAction('move', item)">
<span class="icon"><i class="fa-solid fa-arrows-alt" /></span>
<span>Move</span>
</NuxtLink>
</Dropdown>
</td>
</tr>
</tbody>
</table>
@ -160,17 +202,16 @@ const toast = useNotification()
const config = useConfigStore()
const socket = useSocketStore()
const bg_enable = useStorage('random_bg', true)
const bg_opacity = useStorage('random_bg_opacity', 0.85)
const sort_by = useStorage('sort_by', 'name')
const sort_order = useStorage('sort_order', 'asc')
const isLoading = ref(false)
const initialLoad = ref(true)
const items = ref([])
const path = ref(`/${route.params.slug?.length > 0 ? route.params.slug?.join('/') : ''}`)
const bg_enable = useStorage('random_bg', true)
const bg_opacity = useStorage('random_bg_opacity', 0.85)
const sort_by = useStorage('sort_by', 'name')
const sort_order = useStorage('sort_order', 'asc')
const table_container = ref(false)
const search = ref('')
const show_filter = ref(false)
@ -220,7 +261,6 @@ const sortedItems = items => {
return items
}
const model_item = ref()
const closeModel = () => model_item.value = null
@ -297,7 +337,7 @@ const reloadContent = async (dir = '/', fromMounted = false) => {
dir = '/'
}
dir = sTrim(dir, '/')
dir = encodePath(sTrim(dir, '/'))
const response = await request(`/api/file/browser/${sTrim(dir, '/')}`)
@ -328,7 +368,7 @@ const reloadContent = async (dir = '/', fromMounted = false) => {
history.pushState({ path: dir, title: title }, title, stateUrl)
}
useHead({ title: title })
useHead({ title: decodeURIComponent(title) })
} catch (e) {
if (fromMounted) {
return
@ -443,4 +483,119 @@ const toggleFilter = () => {
awaitElement('#search', e => e.focus())
}
const createDirectory = async (dir) => {
if (!config.app.browser_control_enabled) {
return
}
const newDir = prompt('Enter new directory name:', '')
if (!newDir) {
return
}
let new_dir = sTrim(newDir, '/')
if (!new_dir || new_dir === dir) {
return
}
await actionRequest({ path: dir }, 'directory', { new_dir: new_dir }, (item, action, data) => {
reloadContent(path.value, true)
toast.success(`Successfully created '${new_dir}'.`)
})
}
const handleAction = async (action, item) => {
if (!config.app.browser_control_enabled) {
return
}
if ('rename' === action) {
const newName = prompt('Enter new name for the item:', item.name)
if (!newName) {
return
}
let new_name = newName.trim()
if (!new_name || new_name === item.name) {
return
}
await actionRequest(item, 'rename', { new_name: new_name }, (item, action, data) => {
item.name = data.new_name
item.path = item.path.replace(/[^/]+$/, data.new_name)
toast.success(`Renamed '${item.name}'.`)
})
return
}
if ('delete' === action) {
const msg = item.is_dir ? `Delete '${item.name}' and all its contents?` : `Delete file '${item.name}'?`
if (false === confirm(msg)) {
return
}
await actionRequest(item, 'delete', {}, (item, action, data) => {
items.value = items.value.filter(i => i.path !== item.path)
toast.warning(`Deleted '${item.name}'.`)
})
return
}
if ('move' === action) {
const newPath = prompt('Enter new path:', item.path.replace(/[^/]+$/, ''))
if (!newPath) {
return
}
let new_path = sTrim(newPath, '/')
if (!new_path || new_path === item.path) {
return
}
await actionRequest(item, 'move', { new_path: new_path }, (item, action, data) => {
items.value = items.value.filter(i => i.path !== item.path)
toast.success(`Moved '${item.name}' to '${data.new_path}'.`)
})
return
}
}
const actionRequest = async (item, action, data, cb) => {
if (!config.app.browser_control_enabled) {
return
}
if (!item || !action || !data) {
return
}
try {
const response = await request(`/api/file/action/${encodePath(item.path)}`, {
method: 'POST',
body: JSON.stringify({
path: item.path,
action: action,
...data
}),
})
if (!response.ok) {
const error = await response.json()
toast.error(`Failed to perform action: ${error.error || 'Unknown error'}`)
return
}
if (cb && typeof cb === 'function') {
cb(item, action, data)
}
return response
} catch (error) {
console.error(error)
toast.error(`Failed to perform action: ${error.message}`)
}
}
</script>

View file

@ -18,6 +18,7 @@ export const useConfigStore = defineStore('config', () => {
sentry_dsn: null,
console_enabled: false,
browser_enabled: false,
browser_control_enabled: false,
ytdlp_cli: '',
file_logging: false,
is_native: false,