Skip to content

Commit

Permalink
userhash
Browse files Browse the repository at this point in the history
  • Loading branch information
lunaticsm committed Sep 7, 2024
1 parent b986dc2 commit 21c3eb7
Show file tree
Hide file tree
Showing 4 changed files with 263 additions and 132 deletions.
95 changes: 47 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Catbox Uploader

Catbox Uploader is a simple Python library to upload files and URLs to [Catbox.moe](https://catbox.moe), including its temporary storage feature, **Litterbox**.
Catbox Uploader is a simple Python library to upload files and URLs to [Catbox.moe](https://catbox.moe), including its temporary storage feature, **Litterbox**, and album management.

## Installation

Expand All @@ -10,16 +10,23 @@ pip install catbox-uploader

## Usage

### Upload a File to Catbox
### Using Userhash

You can upload files to **Catbox.moe** using the `upload_file` method. The file will be stored permanently.
CatboxUploader supports using a **userhash** directly. You can pass the `userhash` when initializing the `CatboxUploader` and use it for authenticated uploads and album management.

### Initialize with Userhash

```python
from catbox import CatboxUploader

uploader = CatboxUploader()
link = uploader.upload_file('path/to/your/image.png')
print(f'Uploaded file link: {link}')
uploader = CatboxUploader(userhash='your_userhash_here')
```

### Upload a File

```python
link = uploader.upload_file('path/to/your/file.jpg')
print(f'Uploaded file: {link}')
```

### Upload a File to Litterbox (Temporary Storage)
Expand All @@ -32,43 +39,50 @@ Litterbox allows you to upload files for a temporary period, after which the fil
- `24h`: 24 hours
- `72h`: 3 days

Example of uploading a file to Litterbox for 24 hours:

```python
from catbox import CatboxUploader

uploader = CatboxUploader()
link = uploader.upload_to_litterbox('path/to/your/image.png', time='24h')
print(f'Uploaded file link (available for 24 hours): {link}')
link = uploader.upload_to_litterbox('path/to/your/file.jpg', time='24h')
print(f'Uploaded file (available for 24 hours): {link}')
```

### Upload Multiple Files as an Album to Catbox
### Upload Multiple Files as an Album

You can upload multiple files as an album to **Catbox.moe** using the `upload_album` method. This allows you to upload several files at once, and it will return the links for all uploaded files.

```python
from catbox import CatboxUploader

uploader = CatboxUploader()
file_paths = ['file1.jpg', 'file2.jpg', 'file3.jpg']
links = uploader.upload_album(file_paths)
for link in links:
print(f'Uploaded file link: {link}')
```

### Upload a URL to Catbox
### Create and Manage Albums

If you want to upload a file via a URL to **Catbox**, you can use the `upload_url` method.
#### Create an Album

You can create an album with uploaded files, a title, and a description using the `create_album` method:

```python
from catbox import CatboxUploader
album_shortcode = uploader.create_album(file_links, "My Album", "This is a test album")
print(f"Album created: https://catbox.moe/c/{album_shortcode}")
```

#### Edit an Album

You can edit an album by changing its title, description, or the files it contains:

```python
uploader.edit_album(album_shortcode, file_links, "Updated Album Title", "Updated description")
```

#### Delete an Album

You can delete an album by its shortcode:

uploader = CatboxUploader()
link = uploader.upload_url('https://example.com/image.png')
print(f'Uploaded URL link: {link}')
```python
uploader.delete_album(album_shortcode)
```

## Error Handling
### Error Handling

The library comes with built-in exception handling to manage common errors such as timeouts, connection issues, or HTTP errors.

Expand All @@ -79,10 +93,10 @@ If the upload takes too long and exceeds the specified timeout, a `TimeoutError`
```python
from catbox import CatboxUploader, TimeoutError

uploader = CatboxUploader()
uploader = CatboxUploader(userhash='your_userhash_here')
try:
link = uploader.upload_file('path/to/your/image.png', timeout=10)
print(f'Uploaded file link: {link}')
link = uploader.upload_file('path/to/your/file.jpg', timeout=10)
print(f'Uploaded file: {link}')
except TimeoutError:
print("The upload took too long and timed out.")
```
Expand All @@ -94,10 +108,10 @@ If there's a problem connecting to the **Catbox.moe** or **Litterbox** server, a
```python
from catbox import CatboxUploader, ConnectionError

uploader = CatboxUploader()
uploader = CatboxUploader(userhash='your_userhash_here')
try:
link = uploader.upload_file('path/to/your/image.png')
print(f'Uploaded file link: {link}')
link = uploader.upload_file('path/to/your/file.jpg')
print(f'Uploaded file: {link}')
except ConnectionError:
print("Failed to connect to the server.")
```
Expand All @@ -109,29 +123,14 @@ In case of HTTP errors (such as 404 or 500), an `HTTPError` will be raised.
```python
from catbox import CatboxUploader, HTTPError

uploader = CatboxUploader()
uploader = CatboxUploader(userhash='your_userhash_here')
try:
link = uploader.upload_file('path/to/your/image.png')
print(f'Uploaded file link: {link}')
link = uploader.upload_file('path/to/your/file.jpg')
print(f'Uploaded file: {link}')
except HTTPError as he:
print(f"HTTP error occurred: {he}")
```

### Other Errors

For other unexpected errors, a general `CatboxError` will be raised.

```python
from catbox import CatboxUploader, CatboxError

uploader = CatboxUploader()
try:
link = uploader.upload_file('path/to/your/image.png')
print(f'Uploaded file link: {link}')
except CatboxError as e:
print(f"An error occurred: {e}")
```

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='catbox_uploader',
version='1.7',
version='2.0',
packages=find_packages(where="src"),
package_dir={"": "src"},
install_requires=['requests'],
Expand Down
123 changes: 40 additions & 83 deletions src/catbox/catbox.py
Original file line number Diff line number Diff line change
@@ -1,83 +1,40 @@
import requests
from .exceptions import CatboxError, FileNotFoundError, TimeoutError, ConnectionError, HTTPError

class CatboxUploader:
def __init__(self):
self.api_url = 'https://catbox.moe/user/api.php'
self.litterbox_url = 'https://litterbox.catbox.moe/resources/internals/api.php'

def upload_file(self, file_path, timeout=30):
"""
Upload file to Catbox and return the link.
:param file_path: Path to the file to upload.
:param timeout: Timeout in seconds for the upload request.
:return: URL of the uploaded file on Catbox.
"""
try:
with open(file_path, 'rb') as file:
files = {'fileToUpload': file}
data = {'reqtype': 'fileupload'}
response = requests.post(self.api_url, files=files, data=data, timeout=timeout)
response.raise_for_status()
return response.text.strip()
except requests.exceptions.Timeout:
raise TimeoutError(f"Upload request timed out after {timeout} seconds.")
except requests.exceptions.ConnectionError:
raise ConnectionError("Failed to connect to Catbox. The server might be down.")
except requests.exceptions.HTTPError as http_err:
raise HTTPError(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as e:
raise CatboxError(f"An error occurred: {str(e)}")

def upload_to_litterbox(self, file_path, time='1h', timeout=30):
"""
Upload file to Litterbox (temporary storage) and return the link.
:param file_path: Path to the file to upload.
:param time: Duration for which the file will be available. Options: '1h', '12h', '24h', '72h', '1w'.
:param timeout: Timeout in seconds for the upload request.
:return: URL of the uploaded file on Litterbox.
"""
try:
with open(file_path, 'rb') as file:
files = {'fileToUpload': file}
data = {'reqtype': 'fileupload', 'time': time}
response = requests.post(self.litterbox_url, files=files, data=data, timeout=timeout)
response.raise_for_status()
return response.text.strip()
except requests.exceptions.Timeout:
raise TimeoutError(f"Upload to Litterbox timed out after {timeout} seconds.")
except requests.exceptions.ConnectionError:
raise ConnectionError("Failed to connect to Litterbox. The server might be down.")
except requests.exceptions.HTTPError as http_err:
raise HTTPError(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as e:
raise CatboxError(f"An error occurred: {str(e)}")

def upload_album(self, file_paths, timeout=30):
"""
Upload multiple files as an album to Catbox and return their links.
:param file_paths: List of paths to the files to upload.
:param timeout: Timeout in seconds for the upload request.
:return: List of URLs of the uploaded files on Catbox.
"""
uploaded_links = []
try:
for file_path in file_paths:
with open(file_path, 'rb') as file:
files = {'fileToUpload': file}
data = {'reqtype': 'fileupload'}
response = requests.post(self.api_url, files=files, data=data, timeout=timeout)
response.raise_for_status()
uploaded_links.append(response.text.strip())
return uploaded_links
except requests.exceptions.Timeout:
raise TimeoutError(f"Album upload timed out after {timeout} seconds.")
except requests.exceptions.ConnectionError:
raise ConnectionError("Failed to connect to Catbox. The server might be down.")
except requests.exceptions.HTTPError as http_err:
raise HTTPError(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as e:
raise CatboxError(f"An error occurred: {str(e)}")
from .helpers import upload_file, upload_to_litterbox, upload_album, delete_files, create_album, edit_album, delete_album
from .exceptions import CatboxError

class CatboxUploader:
def __init__(self, userhash=None):
"""
Initialize CatboxUploader with optional userhash (similar to API key).
:param userhash: A string containing the userhash for authenticated uploads and album management.
"""
self.userhash = userhash

def upload_file(self, file_path, timeout=30):
return upload_file(file_path, timeout, self.userhash)

def upload_to_litterbox(self, file_path, time='1h', timeout=30):
return upload_to_litterbox(file_path, time, timeout)

def upload_album(self, file_paths, timeout=30):
return upload_album(file_paths, timeout, self.userhash)

def delete_files(self, files):
if not self.userhash:
raise CatboxError("Userhash is required to delete files.")
return delete_files(files, self.userhash)

def create_album(self, files, title, description):
if not self.userhash:
raise CatboxError("Userhash is required to create an album.")
return create_album(files, title, description, self.userhash)

def edit_album(self, shortcode, files, title, description):
if not self.userhash:
raise CatboxError("Userhash is required to edit an album.")
return edit_album(shortcode, files, title, description, self.userhash)

def delete_album(self, shortcode):
if not self.userhash:
raise CatboxError("Userhash is required to delete an album.")
return delete_album(shortcode, self.userhash)
Loading

0 comments on commit 21c3eb7

Please sign in to comment.