b2_make_index/script.py
Lukas Langrock b825d865d2
All checks were successful
Continuous Integration / Generate index.html (push) Successful in 11s
Upload index to bucket directly (#1)
Instead of just creating the file and uploading it to Gitea via workflow, why not upload it directly to the bucket that is meant for? Exactly, so that's what changed.

Reviewed-on: #1
2024-07-24 23:51:16 +02:00

66 lines
1.8 KiB
Python

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")