Skip to content

Instantly share code, notes, and snippets.

@mwufi
Last active October 27, 2024 23:09
Show Gist options
  • Save mwufi/c2d795739817cffc8e4a5e19128d77d2 to your computer and use it in GitHub Desktop.
Save mwufi/c2d795739817cffc8e4a5e19128d77d2 to your computer and use it in GitHub Desktop.
Create a website in 1s
"""
# How to use this
```
> URL=supwrite.com python sup.py mysite.html banger
```
Then you can visit https://banger.supwrite.com to see your site.
# How it works
Technicall, you don't have to use this script, but it just stores the token for you :)
Basically equivalent of doing this:
```sh
echo '<!DOCTYPE html>
<html>
<head>
<title>Hello Anon</title>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: system-ui, sans-serif;
}
</style>
</head>
<body>
<h1>hello anon!</h1>
</body>
</html>' > index.html
curl -X POST https://anon.supwrite.com \
-H "Content-Type: text/html" \
--data-binary @index.html
```
"""
import argparse
import json
import os
from pathlib import Path
import requests
def validate_subdomain(subdomain):
if not all(c.isalnum() or c == "-" for c in subdomain):
print("Error: Subdomain can only contain letters, numbers, and hyphens")
return False
return True
class SiteUploader:
def __init__(self):
self.tokens_file = "tokens.json"
self.base_url = os.getenv(
"URL", "localhost:8787"
) # Default to 8787 if URL not set
# Ensure the URL has a protocol
if not self.base_url.startswith(("http://", "https://")):
self.base_url = f"http://{self.base_url}"
self.tokens = self.load_tokens()
def load_tokens(self):
"""Load existing tokens from JSON file."""
if os.path.exists(self.tokens_file):
with open(self.tokens_file, "r") as f:
return json.load(f)
return {}
def save_tokens(self):
"""Save tokens to JSON file."""
with open(self.tokens_file, "w") as f:
json.dump(self.tokens, f, indent=2)
def upload_site(self, html_file, subdomain):
"""Upload or update an HTML file."""
if not validate_subdomain(subdomain):
raise ValueError("Invalid subdomain")
# Read the HTML content
with open(html_file, "r", encoding="utf-8") as f:
html_content = f.read()
# Prepare headers
headers = {}
if subdomain in self.tokens:
headers["Authorization"] = self.tokens[subdomain]
# Make the POST request
try:
# Add subdomain to the base URL while preserving protocol
url = self.base_url
if "://" in url:
protocol, base = url.split("://", 1)
url = f"{protocol}://{subdomain}.{base}"
else:
url = f"http://{subdomain}.{url}"
print(f"Uploading to {url}")
response = requests.post(url, data=html_content, headers=headers)
if response.status_code == 200:
# Parse the response to get the token
token = response.json()["token"]
# Save the token if it's new
if subdomain not in self.tokens:
self.tokens[subdomain] = token
self.save_tokens()
print(f"New token received and saved for {subdomain}")
else:
print(f"Site updated successfully for {subdomain}")
print(f"Token: {token}")
return True
else:
print(f"Error: {response.status_code} - {response.text}")
return False
except requests.exceptions.RequestException as e:
print(f"Connection error: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="Upload or update HTML sites")
parser.add_argument("html_file", help="Path to the HTML file")
parser.add_argument("subdomain", help="Subdomain for the site")
args = parser.parse_args()
# Verify the HTML file exists
if not Path(args.html_file).is_file():
print(f"Error: HTML file '{args.html_file}' not found")
return
uploader = SiteUploader()
uploader.upload_site(args.html_file, args.subdomain)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment