Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ on:
tags:
- "v*"

env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
ci:
uses: ./.github/workflows/ci.yml
Expand Down
28 changes: 26 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ on:
branches: ["main"]
workflow_call:

env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
build:
runs-on: ubuntu-latest
Expand Down Expand Up @@ -73,6 +76,26 @@ jobs:
- name: Security (Bandit)
run: uv run bandit -r filebin/ -ll

codeql:
name: CodeQL
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: python
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:python"


test:
runs-on: ubuntu-latest
steps:
Expand All @@ -98,12 +121,13 @@ jobs:
token: ${{ secrets.CODECOV_TOKEN }}
- name: Upload test results to Codecov
if: ${{ !cancelled() }}
uses: codecov/test-results-action@v1
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
report_type: test_results

publish-testpypi:
needs: [build, lint, static, security, test]
needs: [build, lint, static, security, codeql, test]
if: github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest

Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ on:
push:
branches: ["main"]

env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

permissions:
contents: write

Expand Down
42 changes: 23 additions & 19 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
MIT License
Copyright (c) 2024, Aaron Fredrick and Filebin Python Client Contributors
Copyright (c) 2015-2020, Espen Braastad (Original Filebin.net engine)
All rights reserved.

Copyright (c) 2024 Aaron Fredrick
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# Filebin.net Python SDK
# Filebin.net Python Client

![CI](https://github.com/aaron-fredrick/filebin/actions/workflows/ci.yml/badge.svg)
![PyPI](https://img.shields.io/pypi/v/filebin)

A complete, typed, async-first Python SDK and CLI for the [Filebin.net](https://filebin.net/) API.
A complete, typed, async-first Python client and CLI for the [Filebin.net](https://filebin.net/) API.

*Note: This is an unofficial, community-driven Python wrapper for Filebin, not affiliated with the official filebin.net service.*

## Installation

Expand All @@ -16,7 +18,7 @@ With CLI formatting support:
pip install filebin[cli-pretty]
```

## Quick SDK Usage
## Quick Client Usage

```python
import asyncio
Expand Down
88 changes: 88 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Filebin Python Client & CLI

Welcome to the official documentation for the **Filebin Python Client**. This library provides a complete, typed, async-first Python interface and Command-Line Interface (CLI) for the [Filebin.net](https://filebin.net/) API.

*Note: This is an unofficial, community-driven Python wrapper for Filebin, not affiliated with the official filebin.net service.*

## Key Features

- **Async First:** Built on `aiohttp` for high-performance, non-blocking I/O.
- **Sync Support:** A fully synchronous client (`SyncFilebinClient`) is also provided for standard blocking scripts.
- **Robust Error Handling:** Meticulous mapping of HTTP status codes to Python exceptions (`AuthenticationError`, `UploadValidationError`, etc.) based directly on the Filebin engine.
- **Strict Typing:** Extensively annotated with Python type hints for excellent IDE support and `mypy` compatibility.
- **CLI Included:** A powerful CLI tool (`fbin`) is bundled for easy use directly from your terminal.

## Installation

Install the package via pip:

```bash
pip install filebin
```

To include the rich formatting dependencies for the CLI:

```bash
pip install filebin[cli-pretty]
```

## Quick Start (Python)

### Asynchronous Client

```python
import asyncio
from filebin import AsyncFilebinClient

async def main():
async with AsyncFilebinClient() as client:
# Generate a valid local bin ID or validate a custom one
bin_model = client.create_bin("my-custom-bin-id")

# Upload a file
file = await client.upload_file(bin_model.id, "document.pdf")
print(f"Uploaded: {file.filename}")

# List files in a bin
bin_meta = await client.list_bin(bin_model.id)
for f in bin_meta.files:
print(f.filename)

if __name__ == "__main__":
asyncio.run(main())
```

### Synchronous Client

```python
from filebin import SyncFilebinClient

client = SyncFilebinClient()

# Create a bin and upload
bin_model = client.create_bin("my-sync-bin")
file = client.upload_file(bin_model.id, "report.csv")
print(f"Uploaded {file.filename} to {bin_model.id}")
```

## Quick Start (CLI)

```bash
# Upload a file (bin ID is automatically generated if omitted)
fbin upload document.pdf --bin my-bin-id

# Download a file
fbin download my-bin-id document.pdf

# List contents
fbin list my-bin-id

# Create a bin
fbin create-bin --bin my-custom-bin-id
```

## Next Steps

- Check out the **[API Reference](api/client.md)** for detailed method signatures.
- Read about the **[CLI Usage](cli/usage.md)**.
- Understand the **[Architecture](architecture/overview.md)** and design decisions behind the client.
7 changes: 5 additions & 2 deletions filebin/__version__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from importlib.metadata import version
from importlib.metadata import PackageNotFoundError, version

__version__ = version("filebin")
try:
__version__ = version("filebin")
except PackageNotFoundError:
__version__ = "1.0.0"
25 changes: 17 additions & 8 deletions filebin/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ async def cmd_upload(args: argparse.Namespace, client: AsyncFilebinClient) -> No
output.print_error(f"File not found: {path}")
return

# If no bin provided, Filebin.net assigns one dynamically, but our strict typed
# client expects an ID. We let the HTTP layer POST to / if bin_id is missing,
# then redirect catches the new bin ID.
# For now, require it or generate a local random one for simplicity.
if not bin_id:
import uuid

bin_id = uuid.uuid4().hex[:16]
# Generate or validate bin ID using the client's create_bin method
try:
bin_model = await client.create_bin(bin_id)
bin_id = bin_model.id
except ValueError as e:
output.print_error(str(e))
return

file_model = await client.upload_file(bin_id, path)
output.print_success(f"Uploaded {file_model.filename} to bin {bin_id}")
Expand Down Expand Up @@ -57,3 +56,13 @@ async def cmd_lock(args: argparse.Namespace, client: AsyncFilebinClient) -> None
bin_model = await client.lock_bin(args.bin)
output.print_success(f"Locked bin {bin_model.id}")
output.print_bin(bin_model)


async def cmd_create_bin(args: argparse.Namespace, client: AsyncFilebinClient) -> None:
try:
bin_model = await client.create_bin(args.bin)
output.print_success(f"Created/Validated bin ID: {bin_model.id}")
if len(bin_model.files) > 0:
output.print_bin(bin_model)
except ValueError as e:
output.print_error(str(e))
6 changes: 6 additions & 0 deletions filebin/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ def build_parser() -> argparse.ArgumentParser:
p_lock = subparsers.add_parser("lock", help="Lock a bin (read-only)")
p_lock.add_argument("bin", help="Bin ID")

# fbin create-bin [--bin <bin>]
p_create = subparsers.add_parser("create-bin", help="Create or validate a local bin ID")
p_create.add_argument("--bin", help="Custom bin ID to validate")

return parser


Expand All @@ -82,6 +86,8 @@ async def _main(args: argparse.Namespace) -> None:
await commands.cmd_archive(args, client)
elif args.command == "lock":
await commands.cmd_lock(args, client)
elif args.command == "create-bin":
await commands.cmd_create_bin(args, client)
except FilebinError as exc:
output.print_error(str(exc))
sys.exit(1)
Expand Down
37 changes: 37 additions & 0 deletions filebin/client/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
from typing import Literal

from filebin.core.config import ClientConfig
from filebin.core.errors import BinNotFoundError
from filebin.core.http import HttpTransport
from filebin.core.validation import generate_bin_id, validate_bin_id
from filebin.models.bin import BinModel
from filebin.models.file import FileModel

Expand Down Expand Up @@ -34,6 +36,41 @@ async def close(self) -> None:
"""Close the underlying HTTP transport session."""
await self._transport.close()

async def create_bin(self, bin_id: str | None = None) -> BinModel:
"""Create a new valid bin locally and fetch its metadata if it exists.

Note: Bins in Filebin are created dynamically upon the first file upload.
This method generates a valid bin ID or validates a provided one. If the bin
already exists, its metadata is fetched and returned.

Args:
bin_id: Optional custom bin ID. If None, a valid random one is generated.

Returns:
A BinModel instance containing the bin_id and any existing metadata.

Raises:
ValueError: If a provided bin_id is invalid.
"""
if bin_id is not None:
validate_bin_id(bin_id)
else:
bin_id = generate_bin_id()

try:
return await self.list_bin(bin_id)
except BinNotFoundError:
# Return a shell BinModel. The backend will actually create the bin on first upload.
return BinModel(
id=bin_id,
readonly=False,
bytes=0,
created_at=None,
updated_at=None,
expired_at=None,
files=[],
)

async def upload_file(self, bin_id: str, path: Path | str) -> FileModel:
"""Upload a local file to a bin."""
path_obj = Path(path)
Expand Down
39 changes: 39 additions & 0 deletions filebin/client/sync_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,45 @@ class FilebinClient:
def __init__(self, config: ClientConfig | None = None) -> None:
self.config = config or ClientConfig()

def create_bin(self, bin_id: str | None = None) -> BinModel:
"""Create a new valid bin locally and fetch its metadata if it exists.

Note: Bins in Filebin are created dynamically upon the first file upload.
This method generates a valid bin ID or validates a provided one. If the bin
already exists, its metadata is fetched and returned.

Args:
bin_id: Optional custom bin ID. If None, a valid random one is generated.

Returns:
A BinModel instance containing the bin_id and any existing metadata.

Raises:
ValueError: If a provided bin_id is invalid.
"""
# Since create_bin is a synchronous local operation, we don't need the async loop
# Wait, if we fetch metadata, we do need the async loop
from filebin.core.errors import BinNotFoundError
from filebin.core.validation import generate_bin_id, validate_bin_id

if bin_id is not None:
validate_bin_id(bin_id)
else:
bin_id = generate_bin_id()

try:
return self.list_bin(bin_id)
except BinNotFoundError:
return BinModel(
id=bin_id,
readonly=False,
bytes=0,
created_at=None,
updated_at=None,
expired_at=None,
files=[],
)

def upload_file(self, bin_id: str, path: Path | str) -> FileModel:
"""Upload a local file to a bin."""
_guard_no_running_loop()
Expand Down
Loading
Loading