b2_make_index/script.py

66 lines
1.8 KiB
Python
Raw Permalink Normal View History

2024-06-25 13:56:05 +02:00
import os
from b2sdk.v2 import InMemoryAccountInfo, B2Api
from jinja2 import Template
from urllib.parse import quote
# Initialize B2 API
info = InMemoryAccountInfo()
b2_api = B2Api(info)
# Replace these with your B2 credentials and bucket name
application_key_id = os.environ['APPLICATION_KEY_ID']
application_key = os.environ['APPLICATION_KEY']
bucket_name = os.environ['BUCKET_NAME'] # uwu69420
# Authorize with B2
b2_api.authorize_account("production", application_key_id, application_key)
# Get the bucket
bucket = b2_api.get_bucket_by_name(bucket_name)
# List all files in the bucket
file_names = []
for file_version_info in bucket.ls(recursive=True):
file_version, folder_name = file_version_info
if file_version.file_name != "index.html":
file_names.append(file_version.file_name)
# Base URL for public access (replace with your bucket's base URL)
base_url = os.environ['BASE_URL'] # https://f003.backblazeb2.com/file/uwu69420/
# Collect file links
file_links = [(f"{base_url}{quote(file_name)}", file_name) for file_name in file_names]
# HTML Template
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bucket File List</title>
</head>
<body>
<h1>Files in {{ bucket_name }}</h1>
<ul>
{% for link, name in file_links %}
<li><a href="{{ link }}">{{ name }}</a></li>
{% endfor %}
</ul>
</body>
</html>
"""
# Render HTML with Jinja2
template = Template(html_template)
html_content = template.render(bucket_name=bucket_name, file_links=file_links)
# Save HTML to file
output_file = 'index.html'
with open(output_file, 'w') as f:
f.write(html_content)
# Upload file to bucket
bucket.upload_local_file(local_file=output_file, file_name="index.html")
2024-06-25 13:56:05 +02:00