kcfinder-client 0.2.0__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kcfinder_client-0.2.2/.github/workflows/ci.yml +46 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/.github/workflows/publish.yml +2 -2
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/.gitignore +2 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/CLAUDE.md +34 -2
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/PKG-INFO +32 -3
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/README.md +28 -1
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/live.py +73 -2
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/pyproject.toml +5 -2
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/_core.py +22 -13
- kcfinder_client-0.2.2/src/kcfinder_client/_retry.py +79 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/async_client.py +45 -14
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/auth.py +13 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/client.py +43 -14
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/models.py +2 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_auth.py +49 -2
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_core.py +25 -0
- kcfinder_client-0.2.2/tests/test_retry.py +229 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/uv.lock +102 -2
- kcfinder_client-0.2.0/.github/workflows/ci.yml +0 -34
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/.markdownlint.rb +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/LICENSE +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/auth.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/bulk.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/directories.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/exceptions.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/files.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/docs/sync.md +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/examples/async_usage.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/examples/sync_usage.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/__init__.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/exceptions.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/src/kcfinder_client/sync.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tasks.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/__init__.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/conftest.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_async_client.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_client.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_exceptions.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_models.py +0 -0
- {kcfinder_client-0.2.0 → kcfinder_client-0.2.2}/tests/test_sync.py +0 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
validate:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
fail-fast: false
|
|
14
|
+
matrix:
|
|
15
|
+
python-version: ["3.12", "3.13", "3.14"]
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v6
|
|
18
|
+
|
|
19
|
+
- name: Install uv
|
|
20
|
+
uses: astral-sh/setup-uv@v8.0.0
|
|
21
|
+
|
|
22
|
+
- name: Set up Python
|
|
23
|
+
run: uv python install ${{ matrix.python-version }}
|
|
24
|
+
|
|
25
|
+
- name: Install dependencies
|
|
26
|
+
run: uv sync --python ${{ matrix.python-version }}
|
|
27
|
+
|
|
28
|
+
- name: Lint
|
|
29
|
+
run: uv run --python ${{ matrix.python-version }} ruff check .
|
|
30
|
+
|
|
31
|
+
- name: Format check
|
|
32
|
+
run: uv run --python ${{ matrix.python-version }} ruff format --check .
|
|
33
|
+
|
|
34
|
+
- name: Typecheck
|
|
35
|
+
run: uv run --python ${{ matrix.python-version }} pyrefly check
|
|
36
|
+
|
|
37
|
+
- name: Test
|
|
38
|
+
run: uv run --python ${{ matrix.python-version }} pytest -v
|
|
39
|
+
|
|
40
|
+
check:
|
|
41
|
+
if: always()
|
|
42
|
+
needs: validate
|
|
43
|
+
runs-on: ubuntu-latest
|
|
44
|
+
steps:
|
|
45
|
+
- name: All matrix legs passed
|
|
46
|
+
run: test "${{ needs.validate.result }}" = "success"
|
|
@@ -12,10 +12,10 @@ jobs:
|
|
|
12
12
|
runs-on: ubuntu-latest
|
|
13
13
|
environment: pypi
|
|
14
14
|
steps:
|
|
15
|
-
- uses: actions/checkout@
|
|
15
|
+
- uses: actions/checkout@v6
|
|
16
16
|
|
|
17
17
|
- name: Install uv
|
|
18
|
-
uses: astral-sh/setup-uv@
|
|
18
|
+
uses: astral-sh/setup-uv@v8.0.0
|
|
19
19
|
|
|
20
20
|
- name: Set up Python
|
|
21
21
|
run: uv python install 3.14
|
|
@@ -135,6 +135,39 @@ One-way push sync on top of the client. Compares local vs remote files by
|
|
|
135
135
|
name + size. Supports dry run. Available in both async (`SyncManager`) and
|
|
136
136
|
sync (`SyncManagerSync`) variants.
|
|
137
137
|
|
|
138
|
+
## Releasing
|
|
139
|
+
|
|
140
|
+
Published to [PyPI](https://pypi.org/project/kcfinder-client/) via trusted
|
|
141
|
+
publishing (OIDC). No API tokens — auth is configured in PyPI account settings.
|
|
142
|
+
|
|
143
|
+
1. Create a `release-v<version>` branch from main
|
|
144
|
+
2. Bump `version` in `pyproject.toml`
|
|
145
|
+
3. Commit, push, and open a PR to main
|
|
146
|
+
4. Merge the PR after CI passes
|
|
147
|
+
5. Create a GitHub release with tag (e.g., `v0.2.1`) targeting main
|
|
148
|
+
6. `.github/workflows/publish.yml` triggers automatically — re-runs all CI
|
|
149
|
+
checks, builds with `uv build`, publishes via `pypa/gh-action-pypi-publish`
|
|
150
|
+
7. Approve the deployment in GitHub Actions UI (required reviewer gate)
|
|
151
|
+
|
|
152
|
+
CI (`.github/workflows/ci.yml`) runs lint, format check, typecheck, and tests
|
|
153
|
+
on every push and PR to main.
|
|
154
|
+
|
|
155
|
+
### Branch Protection
|
|
156
|
+
|
|
157
|
+
- **`main` branch**: Required status check (`check`, strict). Force pushes
|
|
158
|
+
and branch deletion blocked. Admin bypass is currently allowed.
|
|
159
|
+
- **`pypi` environment**: Deployments restricted to `main` branch and `v*`
|
|
160
|
+
tags. Requires approval from `cyberops7` before publishing proceeds.
|
|
161
|
+
- **Local pre-push hook**: Prevents direct pushes to main from this clone
|
|
162
|
+
(`.git/hooks/pre-push`). Not shared — each clone must set up its own.
|
|
163
|
+
|
|
164
|
+
## Workflow
|
|
165
|
+
|
|
166
|
+
- One PR per issue. Branch naming: `issue-<number>-<short-description>`
|
|
167
|
+
(e.g., `issue-10-stream-uploads`).
|
|
168
|
+
- PRs reference the issue they close (e.g., `Closes #10` in the PR body).
|
|
169
|
+
- All PRs target `main` and must pass the `check` CI status.
|
|
170
|
+
|
|
138
171
|
## Design Principles
|
|
139
172
|
|
|
140
173
|
- Dual sync/async clients sharing logic via `_core.py` (same pattern as
|
|
@@ -142,5 +175,4 @@ sync (`SyncManagerSync`) variants.
|
|
|
142
175
|
- Auth classes take explicit args — no credential sourcing; consumers handle
|
|
143
176
|
that
|
|
144
177
|
- `harmonysite_auth_from_env()` factory for deployment contexts (n8n, CI)
|
|
145
|
-
- Primary consumer is the `witnessmusic` project
|
|
146
|
-
(`uv` source)
|
|
178
|
+
- Primary consumer is the `witnessmusic` project (`uv add kcfinder-client`)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kcfinder-client
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Python client library for KCFinder file manager
|
|
5
5
|
Project-URL: Changelog, https://github.com/cyberops7/kcfinder-client/releases
|
|
6
6
|
Project-URL: Issues, https://github.com/cyberops7/kcfinder-client/issues
|
|
@@ -12,17 +12,19 @@ Classifier: Development Status :: 4 - Beta
|
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
13
|
Classifier: License :: OSI Approved :: MIT License
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
17
|
Classifier: Programming Language :: Python :: 3.14
|
|
16
18
|
Classifier: Topic :: Internet :: WWW/HTTP
|
|
17
19
|
Classifier: Typing :: Typed
|
|
18
|
-
Requires-Python: >=3.
|
|
20
|
+
Requires-Python: >=3.12
|
|
19
21
|
Requires-Dist: httpx>=0.28
|
|
20
22
|
Description-Content-Type: text/markdown
|
|
21
23
|
|
|
22
24
|
# kcfinder-client
|
|
23
25
|
|
|
24
26
|
[](https://github.com/cyberops7/kcfinder-client/actions/workflows/ci.yml)
|
|
25
|
-

|
|
26
28
|
[](https://opensource.org/licenses/MIT)
|
|
27
29
|
|
|
28
30
|
A Python client library for [KCFinder](https://github.com/sunhater/kcfinder),
|
|
@@ -134,6 +136,33 @@ async def main():
|
|
|
134
136
|
asyncio.run(main())
|
|
135
137
|
```
|
|
136
138
|
|
|
139
|
+
## Timeouts & Retries
|
|
140
|
+
|
|
141
|
+
Both clients accept optional `timeout` and `retries` parameters:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from kcfinder_client import KCFinderClient
|
|
145
|
+
|
|
146
|
+
# Set a 30-second timeout
|
|
147
|
+
with KCFinderClient(browse_url, auth, timeout=30.0) as client:
|
|
148
|
+
files = client.list_files()
|
|
149
|
+
|
|
150
|
+
# Retry up to 3 times on connection errors and 5xx responses
|
|
151
|
+
with KCFinderClient(browse_url, auth, retries=3) as client:
|
|
152
|
+
files = client.list_files()
|
|
153
|
+
|
|
154
|
+
# Both together
|
|
155
|
+
with KCFinderClient(browse_url, auth, timeout=30.0, retries=3) as client:
|
|
156
|
+
files = client.list_files()
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
- **`timeout`** — passed to the underlying `httpx` client. Accepts a `float`
|
|
160
|
+
(seconds) or an `httpx.Timeout` object for fine-grained control. Defaults
|
|
161
|
+
to the httpx default of 5 seconds.
|
|
162
|
+
- **`retries`** — number of retry attempts for transient failures (connection
|
|
163
|
+
errors and HTTP 5xx responses). Uses exponential backoff between attempts.
|
|
164
|
+
Defaults to `0` (no retries). Uploads are never retried.
|
|
165
|
+
|
|
137
166
|
## Sync Files with SyncManager
|
|
138
167
|
|
|
139
168
|
One-way push sync to make a remote directory match a local one:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# kcfinder-client
|
|
2
2
|
|
|
3
3
|
[](https://github.com/cyberops7/kcfinder-client/actions/workflows/ci.yml)
|
|
4
|
-

|
|
5
5
|
[](https://opensource.org/licenses/MIT)
|
|
6
6
|
|
|
7
7
|
A Python client library for [KCFinder](https://github.com/sunhater/kcfinder),
|
|
@@ -113,6 +113,33 @@ async def main():
|
|
|
113
113
|
asyncio.run(main())
|
|
114
114
|
```
|
|
115
115
|
|
|
116
|
+
## Timeouts & Retries
|
|
117
|
+
|
|
118
|
+
Both clients accept optional `timeout` and `retries` parameters:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from kcfinder_client import KCFinderClient
|
|
122
|
+
|
|
123
|
+
# Set a 30-second timeout
|
|
124
|
+
with KCFinderClient(browse_url, auth, timeout=30.0) as client:
|
|
125
|
+
files = client.list_files()
|
|
126
|
+
|
|
127
|
+
# Retry up to 3 times on connection errors and 5xx responses
|
|
128
|
+
with KCFinderClient(browse_url, auth, retries=3) as client:
|
|
129
|
+
files = client.list_files()
|
|
130
|
+
|
|
131
|
+
# Both together
|
|
132
|
+
with KCFinderClient(browse_url, auth, timeout=30.0, retries=3) as client:
|
|
133
|
+
files = client.list_files()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- **`timeout`** — passed to the underlying `httpx` client. Accepts a `float`
|
|
137
|
+
(seconds) or an `httpx.Timeout` object for fine-grained control. Defaults
|
|
138
|
+
to the httpx default of 5 seconds.
|
|
139
|
+
- **`retries`** — number of retry attempts for transient failures (connection
|
|
140
|
+
errors and HTTP 5xx responses). Uses exponential backoff between attempts.
|
|
141
|
+
Defaults to `0` (no retries). Uploads are never retried.
|
|
142
|
+
|
|
116
143
|
## Sync Files with SyncManager
|
|
117
144
|
|
|
118
145
|
One-way push sync to make a remote directory match a local one:
|
|
@@ -7,6 +7,7 @@ import tempfile
|
|
|
7
7
|
from contextlib import contextmanager
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
|
+
import httpx
|
|
10
11
|
from dotenv import load_dotenv
|
|
11
12
|
from invoke import task
|
|
12
13
|
|
|
@@ -83,10 +84,33 @@ def _ensure_dir(client: KCFinderClient, name: str) -> None:
|
|
|
83
84
|
|
|
84
85
|
@task
|
|
85
86
|
def auth(c):
|
|
86
|
-
"""Authenticate
|
|
87
|
+
"""Authenticate with valid credentials, then verify bad credentials fail."""
|
|
88
|
+
from kcfinder_client.auth import HarmonySiteAuth
|
|
89
|
+
from kcfinder_client.exceptions import AuthError
|
|
90
|
+
|
|
91
|
+
# Step 1: valid credentials should succeed
|
|
87
92
|
with _get_client() as client:
|
|
88
93
|
tree = client.get_tree()
|
|
89
|
-
print(f"
|
|
94
|
+
print(f"Valid login succeeded. Root: {tree.name}")
|
|
95
|
+
|
|
96
|
+
# Step 2: bad credentials should raise AuthError
|
|
97
|
+
_check_env()
|
|
98
|
+
bad_auth = HarmonySiteAuth(
|
|
99
|
+
login_url=os.environ["KCFINDER_LOGIN_URL"],
|
|
100
|
+
browse_url=os.environ["KCFINDER_BROWSE_URL"],
|
|
101
|
+
username=os.environ["KCFINDER_USERNAME"],
|
|
102
|
+
password="definitely-wrong-password-12345",
|
|
103
|
+
bros_config=os.environ["KCFINDER_BROS_CONFIG"],
|
|
104
|
+
brosseccheck=os.environ.get("KCFINDER_BROSSECCHECK", "Xx-ok-xX"),
|
|
105
|
+
)
|
|
106
|
+
browse_url = os.environ["KCFINDER_BROWSE_URL"]
|
|
107
|
+
try:
|
|
108
|
+
with KCFinderClient(browse_url, bad_auth) as client:
|
|
109
|
+
client.get_tree()
|
|
110
|
+
print("ERROR: Bad credentials were accepted!")
|
|
111
|
+
sys.exit(1)
|
|
112
|
+
except AuthError as e:
|
|
113
|
+
print(f"Bad login rejected: {e}")
|
|
90
114
|
|
|
91
115
|
|
|
92
116
|
# ---------------------------------------------------------------------------
|
|
@@ -427,6 +451,53 @@ def cleanup(c):
|
|
|
427
451
|
print("No test artifacts found.")
|
|
428
452
|
|
|
429
453
|
|
|
454
|
+
@task(name="diagnose-login")
|
|
455
|
+
def diagnose_login(c):
|
|
456
|
+
"""Probe login responses to identify the failure signature.
|
|
457
|
+
|
|
458
|
+
Sends one request with valid credentials and one with a bad password,
|
|
459
|
+
then prints the response details for comparison. Used to determine
|
|
460
|
+
how to detect login failure in HarmonySiteAuth.
|
|
461
|
+
"""
|
|
462
|
+
_check_env()
|
|
463
|
+
login_url = os.environ["KCFINDER_LOGIN_URL"]
|
|
464
|
+
|
|
465
|
+
def _probe(label, password):
|
|
466
|
+
data = {
|
|
467
|
+
"dbase": "users",
|
|
468
|
+
"action": "login",
|
|
469
|
+
"username": os.environ["KCFINDER_USERNAME"],
|
|
470
|
+
"password": password,
|
|
471
|
+
"nextpage": login_url.rsplit("/", 1)[0],
|
|
472
|
+
"login": "Log In",
|
|
473
|
+
"remember": "1",
|
|
474
|
+
}
|
|
475
|
+
with httpx.Client() as client:
|
|
476
|
+
r = client.post(login_url, data=data, follow_redirects=True)
|
|
477
|
+
print(f"\n{'=' * 60}")
|
|
478
|
+
print(f" {label}")
|
|
479
|
+
print(f"{'=' * 60}")
|
|
480
|
+
print(f"status: {r.status_code}")
|
|
481
|
+
print(f"final url: {r.url}")
|
|
482
|
+
history = [(h.status_code, h.headers.get("location")) for h in r.history]
|
|
483
|
+
print(f"history: {history}")
|
|
484
|
+
print(f"resp cookies: {list(r.cookies.keys())}")
|
|
485
|
+
print(f"jar cookies: {dict(client.cookies)}")
|
|
486
|
+
print(f"body len: {len(r.text)}")
|
|
487
|
+
# Look for login-related indicators in the body
|
|
488
|
+
body_lower = r.text.lower()
|
|
489
|
+
print(f"has 'log in' form: {'name="login"' in body_lower}")
|
|
490
|
+
print(f"has 'password' field: {'name="password"' in body_lower}")
|
|
491
|
+
print(f"has 'logged in': {'logged in' in body_lower}")
|
|
492
|
+
print(f"has 'invalid': {'invalid' in body_lower}")
|
|
493
|
+
print(f"has 'incorrect': {'incorrect' in body_lower}")
|
|
494
|
+
print(f"has 'error': {'error' in body_lower}")
|
|
495
|
+
print(f"has 'welcome': {'welcome' in body_lower}")
|
|
496
|
+
|
|
497
|
+
_probe("VALID LOGIN", os.environ["KCFINDER_PASSWORD"])
|
|
498
|
+
_probe("INVALID LOGIN", "definitely-wrong-password-12345")
|
|
499
|
+
|
|
500
|
+
|
|
430
501
|
@task(name="all")
|
|
431
502
|
def all_(c):
|
|
432
503
|
"""Run all live tests in order, stopping on first failure."""
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "kcfinder-client"
|
|
3
|
-
version = "0.2.
|
|
3
|
+
version = "0.2.2"
|
|
4
4
|
description = "Python client library for KCFinder file manager"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
|
-
requires-python = ">=3.
|
|
7
|
+
requires-python = ">=3.12"
|
|
8
8
|
keywords = ["file-manager", "httpx", "kcfinder", "php"]
|
|
9
9
|
classifiers = [
|
|
10
10
|
"Development Status :: 4 - Beta",
|
|
11
11
|
"Intended Audience :: Developers",
|
|
12
12
|
"License :: OSI Approved :: MIT License",
|
|
13
13
|
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
14
16
|
"Programming Language :: Python :: 3.14",
|
|
15
17
|
"Topic :: Internet :: WWW/HTTP",
|
|
16
18
|
"Typing :: Typed",
|
|
@@ -42,6 +44,7 @@ project_excludes = ["tasks.py", "live.py"]
|
|
|
42
44
|
[tool.ruff]
|
|
43
45
|
src = ["src", "tests"]
|
|
44
46
|
line-length = 88
|
|
47
|
+
target-version = "py312"
|
|
45
48
|
|
|
46
49
|
[tool.ruff.lint]
|
|
47
50
|
select = ["E", "F", "I", "N", "W", "UP"]
|
|
@@ -127,7 +127,7 @@ def check_upload_response(response_text: str) -> None:
|
|
|
127
127
|
raise classify_error(action="upload", message=line)
|
|
128
128
|
|
|
129
129
|
|
|
130
|
-
def check_action_error(action: str, response_body:
|
|
130
|
+
def check_action_error(action: str, response_body: object) -> None:
|
|
131
131
|
"""Check a KCFinder response body for errors and raise if found.
|
|
132
132
|
|
|
133
133
|
KCFinder returns HTTP 200 even on errors. Successful mutating actions
|
|
@@ -142,21 +142,30 @@ def check_action_error(action: str, response_body: str | dict) -> None:
|
|
|
142
142
|
msg = "; ".join(err) if isinstance(err, list) else str(err)
|
|
143
143
|
raise classify_error(action=action, message=msg)
|
|
144
144
|
return # empty dict or success dict without "error" key
|
|
145
|
-
if isinstance(response_body, str):
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
145
|
+
if not isinstance(response_body, str):
|
|
146
|
+
raise classify_error(
|
|
147
|
+
action=action,
|
|
148
|
+
message=f"unexpected response type: {type(response_body).__name__}",
|
|
149
|
+
)
|
|
150
|
+
stripped = response_body.strip()
|
|
151
|
+
if stripped == "" or stripped == "{}":
|
|
152
|
+
return
|
|
153
|
+
# Try to parse as JSON — some actions return JSON error strings
|
|
154
|
+
try:
|
|
155
|
+
parsed = json.loads(stripped)
|
|
156
|
+
if isinstance(parsed, dict):
|
|
157
|
+
if "error" in parsed:
|
|
153
158
|
err = parsed["error"]
|
|
154
159
|
msg = "; ".join(err) if isinstance(err, list) else str(err)
|
|
155
160
|
raise classify_error(action=action, message=msg)
|
|
156
|
-
return # valid JSON without "error" key
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
161
|
+
return # valid JSON dict without "error" key
|
|
162
|
+
raise classify_error(
|
|
163
|
+
action=action,
|
|
164
|
+
message=f"unexpected response type: {type(parsed).__name__}",
|
|
165
|
+
)
|
|
166
|
+
except json.JSONDecodeError:
|
|
167
|
+
pass
|
|
168
|
+
raise classify_error(action=action, message=stripped)
|
|
160
169
|
|
|
161
170
|
|
|
162
171
|
def parse_expand_response(raw: dict) -> list[DirTree]:
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Retry decorators for transient HTTP failures."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import functools
|
|
7
|
+
import time
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
|
|
15
|
+
TRANSIENT_EXC = (
|
|
16
|
+
httpx.ConnectError,
|
|
17
|
+
httpx.ReadError,
|
|
18
|
+
httpx.RemoteProtocolError,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _is_transient_response(r: httpx.Response) -> bool:
|
|
23
|
+
return 500 <= r.status_code < 600
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _backoff_seconds(attempt: int) -> float:
|
|
27
|
+
return 0.5 * (2**attempt)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def with_retry(method: Callable) -> Callable:
|
|
31
|
+
"""Retry decorator for sync client methods.
|
|
32
|
+
|
|
33
|
+
Reads ``self._retries`` from the instance to determine the maximum
|
|
34
|
+
number of retry attempts. Retries on connection errors and 5xx
|
|
35
|
+
responses with exponential backoff.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
@functools.wraps(method)
|
|
39
|
+
def wrapper(self, *args, **kwargs):
|
|
40
|
+
last_exc: Exception | None = None
|
|
41
|
+
for attempt in range(self._retries + 1):
|
|
42
|
+
try:
|
|
43
|
+
resp = method(self, *args, **kwargs)
|
|
44
|
+
except TRANSIENT_EXC as e:
|
|
45
|
+
last_exc = e
|
|
46
|
+
else:
|
|
47
|
+
if not _is_transient_response(resp) or attempt == self._retries:
|
|
48
|
+
return resp
|
|
49
|
+
last_exc = None
|
|
50
|
+
if attempt < self._retries:
|
|
51
|
+
time.sleep(_backoff_seconds(attempt))
|
|
52
|
+
raise last_exc # type: ignore[misc]
|
|
53
|
+
|
|
54
|
+
return wrapper
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def with_retry_async(method: Callable) -> Callable:
|
|
58
|
+
"""Retry decorator for async client methods.
|
|
59
|
+
|
|
60
|
+
Async counterpart of :func:`with_retry`.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
@functools.wraps(method)
|
|
64
|
+
async def wrapper(self, *args, **kwargs):
|
|
65
|
+
last_exc: Exception | None = None
|
|
66
|
+
for attempt in range(self._retries + 1):
|
|
67
|
+
try:
|
|
68
|
+
resp = await method(self, *args, **kwargs)
|
|
69
|
+
except TRANSIENT_EXC as e:
|
|
70
|
+
last_exc = e
|
|
71
|
+
else:
|
|
72
|
+
if not _is_transient_response(resp) or attempt == self._retries:
|
|
73
|
+
return resp
|
|
74
|
+
last_exc = None
|
|
75
|
+
if attempt < self._retries:
|
|
76
|
+
await asyncio.sleep(_backoff_seconds(attempt))
|
|
77
|
+
raise last_exc # type: ignore[misc]
|
|
78
|
+
|
|
79
|
+
return wrapper
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"""Async client for KCFinder file manager operations."""
|
|
2
2
|
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
3
5
|
from pathlib import Path
|
|
4
6
|
from types import TracebackType
|
|
5
7
|
from urllib.parse import urlencode
|
|
@@ -18,6 +20,7 @@ from kcfinder_client._core import (
|
|
|
18
20
|
prefix_dir,
|
|
19
21
|
prefix_file_paths,
|
|
20
22
|
)
|
|
23
|
+
from kcfinder_client._retry import with_retry_async
|
|
21
24
|
from kcfinder_client.auth import BaseAuth
|
|
22
25
|
from kcfinder_client.models import DirTree, FileInfo
|
|
23
26
|
|
|
@@ -30,14 +33,20 @@ class AsyncKCFinderClient:
|
|
|
30
33
|
browse_url: str,
|
|
31
34
|
auth: BaseAuth,
|
|
32
35
|
file_type: str = "images",
|
|
36
|
+
timeout: float | httpx.Timeout | None = None,
|
|
37
|
+
retries: int = 0,
|
|
33
38
|
) -> None:
|
|
34
39
|
self._browse_url = browse_url
|
|
35
40
|
self._auth = auth
|
|
36
41
|
self._file_type = file_type
|
|
42
|
+
self._timeout = timeout
|
|
43
|
+
self._retries = retries
|
|
37
44
|
self._client: httpx.AsyncClient | None = None
|
|
38
45
|
|
|
39
46
|
async def __aenter__(self) -> AsyncKCFinderClient:
|
|
40
|
-
self._client = httpx.AsyncClient(
|
|
47
|
+
self._client = httpx.AsyncClient(
|
|
48
|
+
timeout=self._timeout if self._timeout is not None else httpx.Timeout(5.0),
|
|
49
|
+
)
|
|
41
50
|
await self._auth.authenticate(self._client)
|
|
42
51
|
return self
|
|
43
52
|
|
|
@@ -58,7 +67,10 @@ class AsyncKCFinderClient:
|
|
|
58
67
|
)
|
|
59
68
|
return self._client
|
|
60
69
|
|
|
61
|
-
|
|
70
|
+
@with_retry_async
|
|
71
|
+
async def _post(
|
|
72
|
+
self, action: str, data: dict[str, str | list[str]]
|
|
73
|
+
) -> httpx.Response:
|
|
62
74
|
"""Send a POST request to KCFinder."""
|
|
63
75
|
url = build_action_url(
|
|
64
76
|
self._browse_url, action, self._file_type, self._auth.get_query_params()
|
|
@@ -66,6 +78,12 @@ class AsyncKCFinderClient:
|
|
|
66
78
|
headers = build_headers(self._auth.get_referer())
|
|
67
79
|
return await self._get_client().post(url, data=data, headers=headers)
|
|
68
80
|
|
|
81
|
+
@with_retry_async
|
|
82
|
+
async def _get(self, url: str) -> httpx.Response:
|
|
83
|
+
"""Send a GET request to KCFinder."""
|
|
84
|
+
headers = build_headers(self._auth.get_referer())
|
|
85
|
+
return await self._get_client().get(url, headers=headers)
|
|
86
|
+
|
|
69
87
|
async def list_files(self, dir: str = "") -> list[FileInfo]:
|
|
70
88
|
"""List files in a directory (root by default)."""
|
|
71
89
|
data = build_form_data(dir=prefix_dir(self._file_type, dir))
|
|
@@ -81,13 +99,22 @@ class AsyncKCFinderClient:
|
|
|
81
99
|
)
|
|
82
100
|
url += "&" + urlencode({"dir": prefix_dir(self._file_type, dir)})
|
|
83
101
|
headers = build_headers(self._auth.get_referer())
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
102
|
+
file_handles = []
|
|
103
|
+
try:
|
|
104
|
+
for f in files:
|
|
105
|
+
file_handles.append(f.open("rb"))
|
|
106
|
+
upload_files = [
|
|
107
|
+
("upload[]", (f.name, fh)) for f, fh in zip(files, file_handles)
|
|
108
|
+
]
|
|
109
|
+
response = await self._get_client().post(
|
|
110
|
+
url,
|
|
111
|
+
files=upload_files,
|
|
112
|
+
headers=headers,
|
|
113
|
+
)
|
|
114
|
+
check_upload_response(response.text)
|
|
115
|
+
finally:
|
|
116
|
+
for fh in file_handles:
|
|
117
|
+
fh.close()
|
|
91
118
|
|
|
92
119
|
async def delete(self, dir: str, file: str) -> None:
|
|
93
120
|
"""Delete a file."""
|
|
@@ -125,18 +152,22 @@ class AsyncKCFinderClient:
|
|
|
125
152
|
"file": file,
|
|
126
153
|
}
|
|
127
154
|
url = f"{self._browse_url}?{urlencode(params)}"
|
|
128
|
-
|
|
129
|
-
response = await self._get_client().get(url, headers=headers)
|
|
155
|
+
response = await self._get(url)
|
|
130
156
|
return response.content
|
|
131
157
|
|
|
132
158
|
async def get_tree(self) -> DirTree:
|
|
133
159
|
"""Initialize the browser view and return the root directory node."""
|
|
160
|
+
response = await self._post_no_data("init")
|
|
161
|
+
return parse_dir_tree(response.json())
|
|
162
|
+
|
|
163
|
+
@with_retry_async
|
|
164
|
+
async def _post_no_data(self, action: str) -> httpx.Response:
|
|
165
|
+
"""Send a POST request without form data."""
|
|
134
166
|
url = build_action_url(
|
|
135
|
-
self._browse_url,
|
|
167
|
+
self._browse_url, action, self._file_type, self._auth.get_query_params()
|
|
136
168
|
)
|
|
137
169
|
headers = build_headers(self._auth.get_referer())
|
|
138
|
-
|
|
139
|
-
return parse_dir_tree(response.json())
|
|
170
|
+
return await self._get_client().post(url, headers=headers)
|
|
140
171
|
|
|
141
172
|
async def expand(self, dir: str = "") -> list[DirTree]:
|
|
142
173
|
"""Get subdirectory info for a directory (root by default)."""
|
|
@@ -88,6 +88,15 @@ class HarmonySiteAuth(BaseAuth):
|
|
|
88
88
|
"remember": "1",
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
def _login_succeeded(self, session_cookies: httpx.Cookies) -> bool:
|
|
92
|
+
"""Check whether the HarmonySite login actually succeeded.
|
|
93
|
+
|
|
94
|
+
HarmonySite returns HTTP 200 even on bad credentials. A successful
|
|
95
|
+
login sets additional cookies (e.g. ``fakelevel``) beyond
|
|
96
|
+
``PHPSESSID``; a failed login only sets ``PHPSESSID``.
|
|
97
|
+
"""
|
|
98
|
+
return len(session_cookies) > 1
|
|
99
|
+
|
|
91
100
|
async def authenticate(self, session: httpx.AsyncClient) -> None:
|
|
92
101
|
login_resp = await session.post(
|
|
93
102
|
self._login_url,
|
|
@@ -96,6 +105,8 @@ class HarmonySiteAuth(BaseAuth):
|
|
|
96
105
|
)
|
|
97
106
|
if login_resp.status_code != 200:
|
|
98
107
|
raise AuthError(f"Login failed with status {login_resp.status_code}")
|
|
108
|
+
if not self._login_succeeded(session.cookies):
|
|
109
|
+
raise AuthError("Login failed: invalid credentials")
|
|
99
110
|
|
|
100
111
|
init_resp = await session.get(self._init_url())
|
|
101
112
|
if init_resp.status_code != 200:
|
|
@@ -111,6 +122,8 @@ class HarmonySiteAuth(BaseAuth):
|
|
|
111
122
|
)
|
|
112
123
|
if login_resp.status_code != 200:
|
|
113
124
|
raise AuthError(f"Login failed with status {login_resp.status_code}")
|
|
125
|
+
if not self._login_succeeded(session.cookies):
|
|
126
|
+
raise AuthError("Login failed: invalid credentials")
|
|
114
127
|
|
|
115
128
|
init_resp = session.get(self._init_url())
|
|
116
129
|
if init_resp.status_code != 200:
|