Metadata-Version: 2.4
Name: dj-file-browser-panel
Version: 0.2.0
Summary: A read-only Django Admin file browser panel for Django Control Room
Author: Taufan Budiman
Maintainer: Taufan Budiman
License: MIT
Project-URL: Repository, https://github.com/taufanbudiman/dj-file-browser-panel
Project-URL: Bug Tracker, https://github.com/taufanbudiman/dj-file-browser-panel/issues
Keywords: django,file-browser,admin,panel,filesystem,media
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=4.2
Requires-Dist: dj-control-room-base>=1.6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-django>=4.5.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pytest-xdist>=3.2.0; extra == "dev"
Requires-Dist: ruff>=0.6.0; extra == "dev"
Provides-Extra: build
Requires-Dist: build>=1.0.0; extra == "build"
Requires-Dist: twine>=4.0.0; extra == "build"
Dynamic: license-file

[![Django Control Room Panel](https://img.shields.io/badge/Django%20Control%20Room-Panel-0c4b33?logo=django)](https://djangocontrolroom.com)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python versions](https://img.shields.io/pypi/pyversions/dj-file-browser-panel.svg)](https://pypi.org/project/dj-file-browser-panel/)
[![Coverage](https://img.shields.io/badge/coverage-93%25-brightgreen)](https://github.com/taufanbudiman/dj-file-browser-panel)


# Django File Browser Panel

A strictly **read-only** Django Admin panel for browsing the local filesystem —
`MEDIA_ROOT`, `STATIC_ROOT`, and any other configured roots — without shell
access. Part of the [Django Control Room](https://djangocontrolroom.com)
ecosystem.

Answer "did my upload land?" in two clicks: browse directories, check file
sizes and modified times, and optionally preview small text files — all from
the Django admin.

**Compatible with [dj-control-room](https://djangocontrolroom.com).** Register
this panel in the Control Room to manage it from a centralized dashboard.

- **Official site:** [djangocontrolroom.com](https://djangocontrolroom.com)
- **Panel registry:** [djangocontrolroom.com/panels](https://djangocontrolroom.com/panels)

## Features

- **Browsable roots**: `MEDIA_ROOT` and `STATIC_ROOT` by default, or any list
  of directories via `DJ_FILE_BROWSER_PANEL_SETTINGS["ROOTS"]`.
- **Directory listings**: folders first, then files; name, human-readable
  size, and modified time. Dotfiles are hidden by default; an in-page
  toggle reveals them. Page size is selectable per listing (10–250).
- **Breadcrumbs + pagination**: navigate deep trees; large directories are
  paginated, never loaded whole.
- **File details**: path, size, modified time, MIME type guess, and an
  optional preview — text files inline (size-capped), images and PDF
  embedded via the browser.
- **Hard read-only**: no upload, delete, rename, or chmod — there is no
  mutation code path at all.
- **Path sandboxing**: every path is resolved and must stay inside a
  configured root. `..` traversal, absolute paths outside roots, and symlink
  escapes are rejected; escaping symlinks render as disabled entries.
- **No models, no migrations**: `managed=False` placeholder only.
- **Django admin styling**: dark mode and admin skins supported through
  `dj-control-room-base`.

## Screenshots

![Directory listing](https://raw.githubusercontent.com/taufanbudiman/dj-file-browser-panel/main/assets/browse.png)

![Image preview](https://raw.githubusercontent.com/taufanbudiman/dj-file-browser-panel/main/assets/preview.png)

## Known limitations

- **Office document previews are not supported yet** — DOCX, XLSX, PPTX,
  ODT and similar formats show metadata only. Rendering them faithfully
  needs either server-side conversion (e.g. LibreOffice → PDF) or
  client-side libraries; both are still under consideration.
- Preview is strictly opt-in (`PREVIEW_ENABLED`) and capped by
  `PREVIEW_MAX_BYTES`; SVG is deliberately excluded from image embeds.
- This panel is intentionally read-only — there is no download button and
  no archive extraction; raw bytes are only served for allowlisted
  preview types.

## Requirements

- Python 3.9+
- Django 4.2+
- `dj-control-room-base` 1.6+

## Installation

```bash
pip install dj-file-browser-panel dj-control-room
```

Add it to `INSTALLED_APPS`, include its URLs, and migrate (the base package
needs it; this panel has no migrations of its own):

```python
INSTALLED_APPS = [
    # ...
    "dj_control_room_base",
    "dj_file_browser_panel",
    "dj_control_room",
    # ...
]
```

```python
urlpatterns = [
    path("admin/dj-control-room-base/", include("dj_control_room_base.urls")),
    path("admin/files/", include("dj_file_browser_panel.urls")),
    path("admin/dj-control-room/", include("dj_control_room.urls")),
    path("admin/", admin.site.urls),
]
```

```bash
python manage.py migrate
```

Then visit `/admin/` and look for the "DJ FILE BROWSER PANEL" section.

## Configuration

```python
DJ_FILE_BROWSER_PANEL_SETTINGS = {
    # None -> MEDIA_ROOT + STATIC_ROOT. Entries may be path strings or
    # {"name": ..., "path": ..., "description": ...} dicts.
    "ROOTS": [
        {"name": "Media", "path": MEDIA_ROOT},
        {"name": "Static", "path": STATIC_ROOT},
        "/var/www/uploads",
    ],
    # Default entries per page; users can override per listing via the
    # in-UI page-size selector (10/25/50/100/250).
    "PAGE_SIZE": 100,
    # Access control (dj-control-room-base permission model). Superusers
    # only by default; set False and/or ALLOWED_GROUPS to widen access.
    "REQUIRE_SUPERUSER": True,
    # File content preview (off by default). Raster images (except SVG)
    # and PDF are embedded inline. PREVIEW_TYPES allowlists *text* preview
    # MIME types (plus any text/* type), capped at PREVIEW_MAX_BYTES.
    "PREVIEW_ENABLED": False,
    "PREVIEW_MAX_BYTES": 262144,
    "PREVIEW_TYPES": [
        "application/json",
        "text/csv",
        "text/plain",
    ],
}
```

All keys are optional; unset keys fall back to the defaults above. Roots
that don't exist or aren't directories are skipped — if none are valid the
panel shows an empty state instead of an error.

Access control follows the `dj-control-room-base` panel permission model —
but note that **only superusers can use this panel by default**
(`REQUIRE_SUPERUSER: True`). Browsing exposes absolute filesystem paths,
file names, sizes, and previewable contents, so think twice before widening
access: any user who can open the panel can enumerate every configured
root, which may include directories outside `MEDIA_ROOT`/`STATIC_ROOT`
(e.g. `/var/www/uploads`). To allow non-superuser staff, set
`"REQUIRE_SUPERUSER": False` and/or restrict to `"ALLOWED_GROUPS"` in
`DJ_FILE_BROWSER_PANEL_SETTINGS`; per-scope `SCOPE_PERMISSIONS` overrides
are also supported. See the
[dj-control-room-base](https://github.com/django-control-room/dj-control-room)
documentation for details.

## Syntax highlighting

`dj-control-room-base` ships the styles for its `dcr-code-viewer` component
and a vendored copy of highlight.js, but highlighting is opt-in per page.
Any panel template that renders code inside
`<pre class="dcr-code-viewer__body"><code class="language-…">` can enable it
by overriding `{% block extrahead %}` — keep `{{ block.super }}` so the base
styles still load:

```django
{% block extrahead %}
{{ block.super }}
<link rel="stylesheet" href="{% static 'dj_control_room_base/vendor/highlight-github-dark.min.css' %}">
<script src="{% static 'dj_control_room_base/vendor/highlight.min.js' %}"></script>
<script src="{% static 'dj_control_room_base/vendor/highlight-python.min.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.dcr-code-viewer__body code').forEach(function (el) {
        hljs.highlightElement(el);
    });
});
</script>
{% endblock %}
```

This is exactly what the index page does for its "Example configuration"
block. Load `highlight-python.min.js` (or another language pack from
`dj_control_room_base/vendor/`) matching the `language-*` class on your
`<code>` element.

If your page reveals code lazily — e.g. inside a collapsible
`<details class="source-preview-details">` — highlight on toggle instead of
on page load, and skip elements already highlighted:

```django
{% block extrahead %}
{{ block.super }}
<link rel="stylesheet" href="{% static 'dj_control_room_base/vendor/highlight-github-dark.min.css' %}">
<script src="{% static 'dj_control_room_base/vendor/highlight.min.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('details.source-preview-details').forEach(function (details) {
        details.addEventListener('toggle', function () {
            if (details.open) {
                details.querySelectorAll('pre.dcr-code-viewer__body code').forEach(function (el) {
                    if (!el.dataset.highlighted) {
                        hljs.highlightElement(el);
                    }
                });
            }
        });
    });
});
</script>
{% endblock %}
```

Newer `dj-control-room-base` releases may expose a `dj_cr_show_source`
context flag you can wrap the block in (`{% if dj_cr_show_source %}`) so the
assets only load when source previewing is active.

Note: these selectors only match `dcr-code-viewer` / `source-preview-details`
markup. This panel's own text preview (`fb-preview` on the file detail page)
is plain `<pre><code>` and is not syntax-highlighted.

## Development

```bash
pip install -e ".[dev]"
pytest   # runs the suite and writes coverage.xml + htmlcov/
ruff check . && ruff format .
```

`example_project/` is a runnable Django project for manual testing:

```bash
cd example_project
python manage.py migrate
python manage.py runserver
# visit http://127.0.0.1:8000/admin/files/
```

Tests run with `pytest-django` against `tmp_path` fixtures — they never touch
the repo root or real media directories. Coverage is enforced at 85%
(`--cov-fail-under=85`) and runs on every push/PR via GitHub Actions.

## Contributing

Contributions are welcome — bug reports, docs fixes, and features alike.

1. **Fork and clone** the repository, then set up a dev environment:

   ```bash
   pip install -e ".[dev]"
   ```

2. **Run the checks locally before pushing:**

   ```bash
   pytest                    # tests + coverage (must stay >= 85%)
   ruff check . && ruff format .
   ```

3. **Open a pull request** against `main` with a short description of the
   change and any relevant context (issue link, screenshots for UI changes).

House rules:

- **Read-only, always.** The panel must never gain upload, delete, rename,
  chmod, or any other filesystem mutation. Every filesystem path must stay
  inside a configured root (`Path.resolve()` + `is_relative_to`) — reject
  `..` traversal, absolute paths outside roots, and symlink escapes.
- Follow the existing `dj-control-room-base` conventions: `PanelPlugin` for
  registration, `panel_base.html` for templates, `dcr-*` design-system
  classes for UI, `DJ_FILE_BROWSER_PANEL_SETTINGS` for configuration.
- Listings must paginate — never load an entire directory into memory.
- Keep tests on `tmp_path` fixtures — never touch the real filesystem in
  tests.

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE)
file for details.
