mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
Showing preview of zip file contents, allowing user to download individual files without full extraction.
This commit is contained in:
parent
d4ef9cf12f
commit
97006f7f12
9 changed files with 660 additions and 3 deletions
|
|
@ -1359,6 +1359,21 @@ export async function deleteFile(paths) {
|
|||
return response
|
||||
}
|
||||
|
||||
export async function getArchiveContents(path) {
|
||||
const response = await apiPost(`${API_URI}/files/zip/contents`, {path});
|
||||
if (response.ok) {
|
||||
const {contents} = await response.json();
|
||||
return contents;
|
||||
}
|
||||
const message = await getErrorMessage(response, 'Could not read archive contents.');
|
||||
toast({type: 'error', title: 'Archive Error', description: message, time: 5000});
|
||||
}
|
||||
|
||||
export function downloadArchiveMember(path, member) {
|
||||
const params = new URLSearchParams({path, member});
|
||||
window.open(`${API_URI}/files/zip/download?${params}`, '_blank');
|
||||
}
|
||||
|
||||
export async function fetchFilesProgress() {
|
||||
const response = await apiGet(`${API_URI}/files/worker_status`);
|
||||
if (response.ok) {
|
||||
|
|
|
|||
121
app/src/components/ArchivePreview.js
Normal file
121
app/src/components/ArchivePreview.js
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import React from "react";
|
||||
import {Icon, Loader, Message, Placeholder, PlaceholderLine} from "semantic-ui-react";
|
||||
import {downloadArchiveMember, getArchiveContents} from "../api";
|
||||
import {fileSuffixIconName, humanFileSize} from "./Common";
|
||||
import {Modal, Segment, Table} from "./Theme";
|
||||
|
||||
function ArchiveEntry({entry, depth, archivePath}) {
|
||||
const [expanded, setExpanded] = React.useState(depth === 0);
|
||||
|
||||
const indent = '\xa0\xa0\xa0\xa0'.repeat(depth);
|
||||
|
||||
if (entry.is_dir) {
|
||||
const folderRows = expanded && entry.children ? entry.children.map((child, i) =>
|
||||
<ArchiveEntry key={child.path || i} entry={child} depth={depth + 1} archivePath={archivePath}/>
|
||||
) : null;
|
||||
|
||||
return <React.Fragment>
|
||||
<Table.Row onClick={() => setExpanded(!expanded)} style={{cursor: 'pointer'}}>
|
||||
<Table.Cell className='file-path'>
|
||||
{indent}
|
||||
<Icon name={expanded ? 'folder open' : 'folder'}/>
|
||||
{entry.name}/
|
||||
</Table.Cell>
|
||||
<Table.Cell collapsing textAlign='right'>
|
||||
—
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
{folderRows}
|
||||
</React.Fragment>
|
||||
}
|
||||
|
||||
const handleDownload = () => {
|
||||
downloadArchiveMember(archivePath, entry.path);
|
||||
};
|
||||
|
||||
return <Table.Row>
|
||||
<Table.Cell className='file-path' onClick={handleDownload} style={{cursor: 'pointer'}}>
|
||||
{indent}
|
||||
<Icon name={fileSuffixIconName(entry.name)}/>
|
||||
{entry.name}
|
||||
{' '}
|
||||
<Icon name='download' size='small' color='grey'/>
|
||||
</Table.Cell>
|
||||
<Table.Cell collapsing textAlign='right'>
|
||||
{humanFileSize(entry.size)}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
}
|
||||
|
||||
function SkeletonRows() {
|
||||
return <React.Fragment>
|
||||
{[1, 2, 3].map(i =>
|
||||
<Table.Row key={i}>
|
||||
<Table.Cell colSpan={2}>
|
||||
<Placeholder><PlaceholderLine/></Placeholder>
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
)}
|
||||
</React.Fragment>
|
||||
}
|
||||
|
||||
export function ArchivePreviewContent({previewFile}) {
|
||||
const [contents, setContents] = React.useState(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [error, setError] = React.useState(null);
|
||||
|
||||
const path = previewFile['primary_path'] || previewFile['path'];
|
||||
|
||||
React.useEffect(() => {
|
||||
const fetchContents = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await getArchiveContents(path);
|
||||
if (result) {
|
||||
setContents(result);
|
||||
} else {
|
||||
setError('Could not read archive contents.');
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e.message || 'Could not read archive contents.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchContents();
|
||||
}, [path]);
|
||||
|
||||
if (error) {
|
||||
return <Modal.Content>
|
||||
<Message negative>
|
||||
<Message.Header>Cannot read archive</Message.Header>
|
||||
<p>{error}</p>
|
||||
</Message>
|
||||
</Modal.Content>
|
||||
}
|
||||
|
||||
return <Modal.Content scrolling>
|
||||
{!loading && contents && <Segment>
|
||||
<Icon name='archive'/>
|
||||
<strong>{contents.total_files}</strong> files,{' '}
|
||||
<strong>{humanFileSize(contents.total_size)}</strong> total
|
||||
</Segment>}
|
||||
<Table striped selectable unstackable>
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.HeaderCell>Name</Table.HeaderCell>
|
||||
<Table.HeaderCell collapsing textAlign='right'>Size</Table.HeaderCell>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{loading
|
||||
? <SkeletonRows/>
|
||||
: contents && contents.entries.map((entry, i) =>
|
||||
<ArchiveEntry key={entry.path || i} entry={entry} depth={0} archivePath={path}/>
|
||||
)
|
||||
}
|
||||
</Table.Body>
|
||||
</Table>
|
||||
</Modal.Content>
|
||||
}
|
||||
|
|
@ -1115,6 +1115,15 @@ export function isZipMimetype(mimetype) {
|
|||
return mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib') || mimetype.startsWith('application/x-7z-compressed') || mimetype.startsWith('application/x-bzip2') || mimetype.startsWith('application/x-xz') || mimetype.startsWith('application/gzip') || mimetype.startsWith('application/x-rar');
|
||||
}
|
||||
|
||||
export function isSupportedArchive(mimetype, lowerPath) {
|
||||
// Zip is always supported.
|
||||
if (mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib')) return true;
|
||||
if (mimetype.startsWith('application/x-tar')) return true;
|
||||
// Suffix-based detection for tar variants whose mimetype may be the compression type.
|
||||
if (lowerPath.endsWith('.tar') || lowerPath.endsWith('.tar.gz') || lowerPath.endsWith('.tgz') || lowerPath.endsWith('.tar.bz2') || lowerPath.endsWith('.tar.xz')) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function mimetypeIconName(mimetype, lowerPath = '') {
|
||||
if (mimetype) {
|
||||
if (mimetype.startsWith('text/html') || mimetype.startsWith('application/json') || mimetype.startsWith('text/yaml') || mimetype.startsWith('text/xml')) {
|
||||
|
|
@ -1179,6 +1188,52 @@ export function mimetypeIconName(mimetype, lowerPath = '') {
|
|||
return 'file';
|
||||
}
|
||||
|
||||
const SUFFIX_ICON_MAP = {
|
||||
// Code
|
||||
html: 'file code', htm: 'file code', json: 'file code', xml: 'file code',
|
||||
yaml: 'file code', yml: 'file code', js: 'file code', css: 'file code',
|
||||
py: 'file code', sh: 'file code', c: 'file code', cpp: 'file code',
|
||||
h: 'file code', java: 'file code', rs: 'file code', go: 'file code',
|
||||
ts: 'file code', tsx: 'file code', jsx: 'file code',
|
||||
// Documents
|
||||
pdf: 'file pdf',
|
||||
txt: 'file text', md: 'file text', csv: 'file text', log: 'file text', rst: 'file text',
|
||||
doc: 'file word', docx: 'file word', odt: 'file word',
|
||||
xls: 'file excel', xlsx: 'file excel', ods: 'file excel',
|
||||
ppt: 'file powerpoint', pptx: 'file powerpoint', odp: 'file powerpoint',
|
||||
// Media
|
||||
jpg: 'image', jpeg: 'image', png: 'image', gif: 'image', svg: 'image',
|
||||
bmp: 'image', webp: 'image', ico: 'image', tiff: 'image',
|
||||
mp4: 'film', mkv: 'film', avi: 'film', mov: 'film', wmv: 'film', webm: 'film', flv: 'film',
|
||||
mp3: 'file audio', wav: 'file audio', flac: 'file audio', ogg: 'file audio',
|
||||
aac: 'file audio', wma: 'file audio', m4a: 'file audio',
|
||||
vtt: 'closed captioning', srt: 'closed captioning',
|
||||
// Archives
|
||||
zip: 'file archive', tar: 'file archive', gz: 'file archive', bz2: 'file archive',
|
||||
xz: 'file archive', '7z': 'file archive', rar: 'file archive', tgz: 'file archive',
|
||||
// Books
|
||||
epub: 'book', mobi: 'book', azw3: 'book',
|
||||
// 3D
|
||||
stl: 'cube', blend: 'cube', scad: 'cube',
|
||||
// Platform
|
||||
exe: 'windows', msi: 'windows',
|
||||
dmg: 'apple',
|
||||
iso: 'dot circle', img: 'dot circle',
|
||||
// Certs
|
||||
pem: 'certificate', crt: 'certificate', cer: 'certificate',
|
||||
// Email
|
||||
eml: 'mail',
|
||||
};
|
||||
|
||||
export function fileSuffixIconName(filename) {
|
||||
const dot = filename.lastIndexOf('.');
|
||||
if (dot >= 0) {
|
||||
const ext = filename.substring(dot + 1).toLowerCase();
|
||||
return SUFFIX_ICON_MAP[ext] || 'file';
|
||||
}
|
||||
return 'file';
|
||||
}
|
||||
|
||||
export function FileIcon({file, disabled = true, size = 'huge', ...props}) {
|
||||
// Default to a grey file icon.
|
||||
const {mimetype, path, primary_path} = file;
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@ import _ from "lodash";
|
|||
import {Grid, Header as SHeader, Image,} from "semantic-ui-react";
|
||||
import {TagsSelector} from "../Tags";
|
||||
import {Media} from "../contexts/contexts";
|
||||
import {encodeMediaPath} from "./Common";
|
||||
import {encodeMediaPath, isSupportedArchive} from "./Common";
|
||||
import {getFile, tagFileGroup, untagFileGroup} from "../api";
|
||||
import {ArchivePreviewContent} from "./ArchivePreview";
|
||||
import {StlViewer} from "react-stl-viewer";
|
||||
import {Button, Modal} from "./Theme";
|
||||
import {toast} from "react-semantic-toasts-2";
|
||||
|
|
@ -360,6 +361,8 @@ export function FilePreviewProvider({children}) {
|
|||
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
|
||||
} else if (mimetype.startsWith('application/octet-stream') && lowerPath.endsWith('.stl')) {
|
||||
setModalContent(getSTLPreviewModal(previewFile), null, downloadURL, path, taggable);
|
||||
} else if (isSupportedArchive(mimetype, lowerPath)) {
|
||||
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
|
||||
} else {
|
||||
// No special handler for this file type, just open it.
|
||||
setModalContent(getGenericPreviewModal(previewFile), url, downloadURL, path, taggable);
|
||||
|
|
|
|||
|
|
@ -199,3 +199,15 @@ class UnknownCollection(APIError):
|
|||
code = 'UNKNOWN_COLLECTION'
|
||||
summary = 'Unable to find the collection'
|
||||
status_code = HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
class UnsupportedArchive(APIError):
|
||||
code = 'UNSUPPORTED_ARCHIVE'
|
||||
summary = 'The file is not a supported archive format.'
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
class InvalidArchiveMember(APIError):
|
||||
code = 'INVALID_ARCHIVE_MEMBER'
|
||||
summary = 'The requested member does not exist in the archive.'
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ from sanic_ext.extensions.openapi import openapi
|
|||
|
||||
from wrolpi.common import get_media_directory, wrol_mode_check, get_relative_to_media_directory, logger, \
|
||||
background_task, walk, timer, TRACE_LEVEL, unique_by_predicate
|
||||
from wrolpi.errors import InvalidFile, UnknownDirectory, FileUploadFailed, FileConflict
|
||||
from wrolpi.errors import InvalidFile, UnknownDirectory, FileUploadFailed, FileConflict, UnsupportedArchive
|
||||
from . import lib, schema
|
||||
from .worker import file_worker
|
||||
from ..api_utils import json_response, api_app
|
||||
|
|
@ -517,3 +517,33 @@ async def post_bulk_tag_apply(_: Request, body: schema.BulkTagApplyRequest):
|
|||
async def get_bulk_tag_progress(_: Request):
|
||||
progress = lib.get_bulk_tag_progress()
|
||||
return json_response(progress.__json__())
|
||||
|
||||
|
||||
@files_bp.post('/zip/contents')
|
||||
@openapi.definition(
|
||||
summary='List the contents of an archive file (zip, tar, tar.gz, etc.)',
|
||||
body=schema.ArchiveContentsRequest,
|
||||
)
|
||||
@validate(schema.ArchiveContentsRequest)
|
||||
async def post_archive_contents(_: Request, body: schema.ArchiveContentsRequest):
|
||||
path = get_media_directory() / body.path
|
||||
contents = lib.list_archive_contents(path)
|
||||
return json_response({'contents': contents})
|
||||
|
||||
|
||||
@files_bp.get('/zip/download')
|
||||
@openapi.definition(
|
||||
summary='Download a single file from inside an archive.',
|
||||
)
|
||||
async def get_archive_download(request: Request):
|
||||
archive_path = request.args.get('path')
|
||||
member = request.args.get('member')
|
||||
if not archive_path or not member:
|
||||
raise InvalidFile('path and member query parameters are required')
|
||||
path = get_media_directory() / archive_path
|
||||
file_bytes, content_type, filename = lib.stream_archive_member(path, member)
|
||||
return response.raw(
|
||||
file_bytes,
|
||||
content_type=content_type,
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,12 +4,15 @@ import datetime
|
|||
import functools
|
||||
import glob
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
from itertools import zip_longest
|
||||
from pathlib import Path
|
||||
from typing import Callable, List, Tuple, Union, Dict, Generator, Iterable, Set
|
||||
|
|
@ -31,7 +34,7 @@ from wrolpi.dates import now, from_timestamp, months_selector_to_where, date_ran
|
|||
from wrolpi.db import get_db_session, get_db_curs, mogrify
|
||||
from wrolpi.downloader import download_manager, Download
|
||||
from wrolpi.errors import InvalidFile, UnknownDirectory, UnknownFile, UnknownTag, FileConflict, FileGroupIsTagged, \
|
||||
NoPrimaryFile, InvalidDirectory, IgnoredDirectoryError
|
||||
NoPrimaryFile, InvalidDirectory, IgnoredDirectoryError, UnsupportedArchive, InvalidArchiveMember
|
||||
from wrolpi.events import Events
|
||||
from wrolpi.files.models import FileGroup, Directory
|
||||
from wrolpi.lang import ISO_639_CODES, ISO_3166_CODES
|
||||
|
|
@ -2076,3 +2079,172 @@ async def bulk_tag_worker():
|
|||
from wrolpi.api_utils import perpetual_signal
|
||||
|
||||
bulk_tag_worker = perpetual_signal(sleep=1)(bulk_tag_worker)
|
||||
|
||||
|
||||
def _detect_archive_type(path: pathlib.Path) -> str:
|
||||
"""Detect archive type from file suffix. Returns 'zip', 'tar', or raises UnsupportedArchive."""
|
||||
name = path.name.lower()
|
||||
if name.endswith('.zip'):
|
||||
return 'zip'
|
||||
if name.endswith(('.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tar.xz')):
|
||||
return 'tar'
|
||||
raise UnsupportedArchive(f'Unsupported archive format: {path.name}')
|
||||
|
||||
|
||||
def _build_tree(entries: list) -> list:
|
||||
"""Build a hierarchical tree from a flat list of archive entries.
|
||||
|
||||
Each entry is a dict with 'path', 'name', 'is_dir', 'size'.
|
||||
Returns a nested list with 'children' on directory entries.
|
||||
"""
|
||||
root_children = []
|
||||
# Map from directory path to its children list.
|
||||
dir_map = {}
|
||||
|
||||
# Sort entries so parents come before children.
|
||||
entries.sort(key=lambda e: e['path'])
|
||||
|
||||
for entry in entries:
|
||||
parts = entry['path'].strip('/').split('/')
|
||||
if len(parts) == 1:
|
||||
# Top-level entry.
|
||||
if entry['is_dir']:
|
||||
entry['children'] = []
|
||||
dir_map[entry['path'].rstrip('/') + '/'] = entry['children']
|
||||
root_children.append(entry)
|
||||
else:
|
||||
# Find parent directory.
|
||||
parent_path = '/'.join(parts[:-1]) + '/'
|
||||
if parent_path not in dir_map:
|
||||
# Create implicit parent directories.
|
||||
current = ''
|
||||
for part in parts[:-1]:
|
||||
current += part + '/'
|
||||
if current not in dir_map:
|
||||
parent_entry = {
|
||||
'path': current,
|
||||
'name': part,
|
||||
'is_dir': True,
|
||||
'size': 0,
|
||||
'children': [],
|
||||
}
|
||||
dir_map[current] = parent_entry['children']
|
||||
# Attach to grandparent or root.
|
||||
grandparent = '/'.join(current.rstrip('/').split('/')[:-1])
|
||||
grandparent_key = grandparent + '/' if grandparent else None
|
||||
if grandparent_key and grandparent_key in dir_map:
|
||||
dir_map[grandparent_key].append(parent_entry)
|
||||
else:
|
||||
root_children.append(parent_entry)
|
||||
|
||||
if entry['is_dir']:
|
||||
entry['children'] = []
|
||||
dir_map[entry['path'].rstrip('/') + '/'] = entry['children']
|
||||
|
||||
parent_list = dir_map.get(parent_path)
|
||||
if parent_list is not None:
|
||||
parent_list.append(entry)
|
||||
else:
|
||||
root_children.append(entry)
|
||||
|
||||
return root_children
|
||||
|
||||
|
||||
def list_archive_contents(path: pathlib.Path) -> dict:
|
||||
"""List the contents of an archive file as a hierarchical tree.
|
||||
|
||||
Returns: {"entries": [...], "total_size": int, "total_files": int}
|
||||
"""
|
||||
media_directory = get_media_directory()
|
||||
if not str(path).startswith(str(media_directory)):
|
||||
raise InvalidFile('Path must be within the media directory')
|
||||
if not path.is_file():
|
||||
raise InvalidFile(f'Archive file does not exist: {path}')
|
||||
|
||||
archive_type = _detect_archive_type(path)
|
||||
flat_entries = []
|
||||
total_size = 0
|
||||
total_files = 0
|
||||
|
||||
try:
|
||||
if archive_type == 'zip':
|
||||
with zipfile.ZipFile(path, 'r') as zf:
|
||||
for info in zf.infolist():
|
||||
is_dir = info.is_dir()
|
||||
entry = {
|
||||
'path': info.filename,
|
||||
'name': info.filename.rstrip('/').split('/')[-1],
|
||||
'is_dir': is_dir,
|
||||
'size': info.file_size,
|
||||
}
|
||||
flat_entries.append(entry)
|
||||
if not is_dir:
|
||||
total_size += info.file_size
|
||||
total_files += 1
|
||||
elif archive_type == 'tar':
|
||||
with tarfile.open(path, 'r:*') as tf:
|
||||
for member in tf.getmembers():
|
||||
is_dir = member.isdir()
|
||||
entry = {
|
||||
'path': member.name + ('/' if is_dir else ''),
|
||||
'name': member.name.rstrip('/').split('/')[-1],
|
||||
'is_dir': is_dir,
|
||||
'size': member.size,
|
||||
}
|
||||
flat_entries.append(entry)
|
||||
if not is_dir:
|
||||
total_size += member.size
|
||||
total_files += 1
|
||||
except (zipfile.BadZipFile, tarfile.TarError, EOFError, OSError) as e:
|
||||
raise UnsupportedArchive(f'Cannot read archive: {e}')
|
||||
|
||||
tree = _build_tree(flat_entries)
|
||||
return {'entries': tree, 'total_size': total_size, 'total_files': total_files}
|
||||
|
||||
|
||||
def stream_archive_member(archive_path: pathlib.Path, member_path: str) -> Tuple[bytes, str, str]:
|
||||
"""Read a single member from an archive and return its bytes, mimetype, and filename.
|
||||
|
||||
Security: validates member_path has no '..' components.
|
||||
"""
|
||||
media_directory = get_media_directory()
|
||||
if not str(archive_path).startswith(str(media_directory)):
|
||||
raise InvalidFile('Path must be within the media directory')
|
||||
if not archive_path.is_file():
|
||||
raise InvalidFile(f'Archive file does not exist: {archive_path}')
|
||||
|
||||
# Security: reject path traversal.
|
||||
if '..' in member_path.split('/'):
|
||||
raise InvalidArchiveMember('Invalid member path: contains ".."')
|
||||
|
||||
archive_type = _detect_archive_type(archive_path)
|
||||
filename = member_path.rstrip('/').split('/')[-1]
|
||||
guessed_type, _ = mimetypes.guess_type(filename)
|
||||
content_type = guessed_type or 'application/octet-stream'
|
||||
|
||||
try:
|
||||
if archive_type == 'zip':
|
||||
with zipfile.ZipFile(archive_path, 'r') as zf:
|
||||
try:
|
||||
info = zf.getinfo(member_path)
|
||||
except KeyError:
|
||||
raise InvalidArchiveMember(f'Member not found in archive: {member_path}')
|
||||
if info.is_dir():
|
||||
raise InvalidArchiveMember(f'Cannot download a directory: {member_path}')
|
||||
file_bytes = zf.read(member_path)
|
||||
elif archive_type == 'tar':
|
||||
with tarfile.open(archive_path, 'r:*') as tf:
|
||||
try:
|
||||
member = tf.getmember(member_path)
|
||||
except KeyError:
|
||||
raise InvalidArchiveMember(f'Member not found in archive: {member_path}')
|
||||
if member.isdir():
|
||||
raise InvalidArchiveMember(f'Cannot download a directory: {member_path}')
|
||||
f = tf.extractfile(member)
|
||||
if f is None:
|
||||
raise InvalidArchiveMember(f'Cannot extract member: {member_path}')
|
||||
file_bytes = f.read()
|
||||
except (zipfile.BadZipFile, tarfile.TarError, EOFError, OSError) as e:
|
||||
raise UnsupportedArchive(f'Cannot read archive: {e}')
|
||||
|
||||
return file_bytes, content_type, filename
|
||||
|
|
|
|||
|
|
@ -98,3 +98,10 @@ class BulkTagApplyRequest:
|
|||
paths: List[str] = field(default_factory=list)
|
||||
add_tag_names: List[str] = field(default_factory=list)
|
||||
remove_tag_names: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArchiveContentsRequest:
|
||||
path: str
|
||||
|
||||
|
||||
|
|
|
|||
242
wrolpi/files/test/test_archive_browse.py
Normal file
242
wrolpi/files/test/test_archive_browse.py
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
import io
|
||||
import json
|
||||
import tarfile
|
||||
import zipfile
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_zip_contents(test_session, async_client, test_directory):
|
||||
"""Zip archive contents can be listed as a tree."""
|
||||
archive_path = test_directory / 'test.zip'
|
||||
with zipfile.ZipFile(archive_path, 'w') as zf:
|
||||
zf.writestr('file1.txt', 'hello')
|
||||
zf.writestr('dir1/file2.txt', 'world')
|
||||
zf.writestr('dir1/file3.txt', 'foo')
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'test.zip'}))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
contents = response.json['contents']
|
||||
assert contents['total_files'] == 3
|
||||
assert contents['total_size'] == len(b'hello') + len(b'world') + len(b'foo')
|
||||
# Should have file1.txt at root and dir1/ with 2 children.
|
||||
entry_names = [e['name'] for e in contents['entries']]
|
||||
assert 'file1.txt' in entry_names
|
||||
assert 'dir1' in entry_names
|
||||
dir1 = [e for e in contents['entries'] if e['name'] == 'dir1'][0]
|
||||
assert dir1['is_dir'] is True
|
||||
assert len(dir1['children']) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_tar_gz_contents(test_session, async_client, test_directory):
|
||||
"""Tar.gz archive contents can be listed."""
|
||||
archive_path = test_directory / 'test.tar.gz'
|
||||
with tarfile.open(archive_path, 'w:gz') as tf:
|
||||
data = b'hello tar'
|
||||
info = tarfile.TarInfo(name='readme.txt')
|
||||
info.size = len(data)
|
||||
tf.addfile(info, io.BytesIO(data))
|
||||
|
||||
data2 = b'nested file'
|
||||
info2 = tarfile.TarInfo(name='subdir/nested.txt')
|
||||
info2.size = len(data2)
|
||||
tf.addfile(info2, io.BytesIO(data2))
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'test.tar.gz'}))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
contents = response.json['contents']
|
||||
assert contents['total_files'] == 2
|
||||
assert contents['total_size'] == len(b'hello tar') + len(b'nested file')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_tar_xz_contents(test_session, async_client, test_directory):
|
||||
"""Tar.xz archive contents can be listed."""
|
||||
archive_path = test_directory / 'test.tar.xz'
|
||||
with tarfile.open(archive_path, 'w:xz') as tf:
|
||||
data = b'xz content'
|
||||
info = tarfile.TarInfo(name='data.bin')
|
||||
info.size = len(data)
|
||||
tf.addfile(info, io.BytesIO(data))
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'test.tar.xz'}))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
contents = response.json['contents']
|
||||
assert contents['total_files'] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_tar_contents(test_session, async_client, test_directory):
|
||||
"""Plain tar archive contents can be listed."""
|
||||
archive_path = test_directory / 'test.tar'
|
||||
with tarfile.open(archive_path, 'w') as tf:
|
||||
data = b'plain tar'
|
||||
info = tarfile.TarInfo(name='plain.txt')
|
||||
info.size = len(data)
|
||||
tf.addfile(info, io.BytesIO(data))
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'test.tar'}))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
contents = response.json['contents']
|
||||
assert contents['total_files'] == 1
|
||||
assert contents['total_size'] == len(b'plain tar')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_tar_bz2_contents(test_session, async_client, test_directory):
|
||||
"""Tar.bz2 archive contents can be listed."""
|
||||
archive_path = test_directory / 'test.tar.bz2'
|
||||
with tarfile.open(archive_path, 'w:bz2') as tf:
|
||||
data = b'bz2 content'
|
||||
info = tarfile.TarInfo(name='bz2file.txt')
|
||||
info.size = len(data)
|
||||
tf.addfile(info, io.BytesIO(data))
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'test.tar.bz2'}))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
contents = response.json['contents']
|
||||
assert contents['total_files'] == 1
|
||||
assert contents['total_size'] == len(b'bz2 content')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_contents_unsupported(test_session, async_client, test_directory):
|
||||
"""Non-archive file returns an error."""
|
||||
txt_path = test_directory / 'readme.txt'
|
||||
txt_path.write_text('not an archive')
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'readme.txt'}))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'UNSUPPORTED_ARCHIVE' in response.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_contents_corrupted(test_session, async_client, test_directory):
|
||||
"""Corrupted archive returns an error."""
|
||||
archive_path = test_directory / 'bad.zip'
|
||||
archive_path.write_bytes(b'this is not a zip file')
|
||||
|
||||
_, response = await async_client.post('/api/files/zip/contents',
|
||||
content=json.dumps({'path': 'bad.zip'}))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'UNSUPPORTED_ARCHIVE' in response.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_single_member_zip(test_session, async_client, test_directory):
|
||||
"""A single file can be streamed from a zip archive."""
|
||||
archive_path = test_directory / 'test.zip'
|
||||
file_content = b'download me'
|
||||
with zipfile.ZipFile(archive_path, 'w') as zf:
|
||||
zf.writestr('docs/readme.txt', file_content)
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.zip&member=docs/readme.txt')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == file_content
|
||||
assert 'readme.txt' in response.headers.get('Content-Disposition', '')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_single_member_tar(test_session, async_client, test_directory):
|
||||
"""A single file can be streamed from a tar archive."""
|
||||
archive_path = test_directory / 'test.tar.gz'
|
||||
file_content = b'tar member content'
|
||||
with tarfile.open(archive_path, 'w:gz') as tf:
|
||||
info = tarfile.TarInfo(name='data/file.dat')
|
||||
info.size = len(file_content)
|
||||
tf.addfile(info, io.BytesIO(file_content))
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.tar.gz&member=data/file.dat')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == file_content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_single_member_tar_plain(test_session, async_client, test_directory):
|
||||
"""A single file can be streamed from a plain tar archive."""
|
||||
archive_path = test_directory / 'test.tar'
|
||||
file_content = b'plain tar member'
|
||||
with tarfile.open(archive_path, 'w') as tf:
|
||||
info = tarfile.TarInfo(name='doc.txt')
|
||||
info.size = len(file_content)
|
||||
tf.addfile(info, io.BytesIO(file_content))
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.tar&member=doc.txt')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == file_content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_single_member_tar_bz2(test_session, async_client, test_directory):
|
||||
"""A single file can be streamed from a tar.bz2 archive."""
|
||||
archive_path = test_directory / 'test.tar.bz2'
|
||||
file_content = b'bz2 member content'
|
||||
with tarfile.open(archive_path, 'w:bz2') as tf:
|
||||
info = tarfile.TarInfo(name='data/info.txt')
|
||||
info.size = len(file_content)
|
||||
tf.addfile(info, io.BytesIO(file_content))
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.tar.bz2&member=data/info.txt')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == file_content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_single_member_tar_xz(test_session, async_client, test_directory):
|
||||
"""A single file can be streamed from a tar.xz archive."""
|
||||
archive_path = test_directory / 'test.tar.xz'
|
||||
file_content = b'xz member content'
|
||||
with tarfile.open(archive_path, 'w:xz') as tf:
|
||||
info = tarfile.TarInfo(name='notes/readme.md')
|
||||
info.size = len(file_content)
|
||||
tf.addfile(info, io.BytesIO(file_content))
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.tar.xz&member=notes/readme.md')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.body == file_content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_nonexistent_member(test_session, async_client, test_directory):
|
||||
"""Requesting a non-existent member returns an error."""
|
||||
archive_path = test_directory / 'test.zip'
|
||||
with zipfile.ZipFile(archive_path, 'w') as zf:
|
||||
zf.writestr('exists.txt', 'data')
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.zip&member=nope.txt')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'INVALID_ARCHIVE_MEMBER' in response.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_directory_member(test_session, async_client, test_directory):
|
||||
"""Attempting to download a directory entry returns an error."""
|
||||
archive_path = test_directory / 'test.zip'
|
||||
with zipfile.ZipFile(archive_path, 'w') as zf:
|
||||
zf.writestr('mydir/', '')
|
||||
zf.writestr('mydir/file.txt', 'content')
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.zip&member=mydir/')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'INVALID_ARCHIVE_MEMBER' in response.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_traversal_attack(test_session, async_client, test_directory):
|
||||
"""Member path with '../' is rejected."""
|
||||
archive_path = test_directory / 'test.zip'
|
||||
with zipfile.ZipFile(archive_path, 'w') as zf:
|
||||
zf.writestr('file.txt', 'safe')
|
||||
|
||||
_, response = await async_client.get('/api/files/zip/download?path=test.zip&member=../../../etc/passwd')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'INVALID_ARCHIVE_MEMBER' in response.text
|
||||
Loading…
Add table
Add a link
Reference in a new issue