import os
import time
import requests
import dotenv
import mistune
from image import fetch_image
dotenv.load_dotenv()
ACCESS_KEY = os.getenv('ACCESS_KEY')
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
REFRESH_TOKEN = os.getenv('REFRESH_TOKEN')
BLOG_ID = os.getenv('BLOG_ID')
def generate_post_html(doi, title, category, summary, mindmap, citation):
doi = doi.split("https://")[-1]
mindmap = mindmap.replace("{", r'{').replace("}", r'}')
citation_clean = citation.replace("&", "&").replace("```plaintext\n", "").replace("\n```", "").strip()
citation_html = mistune.html(repr(citation_clean)[1:-1])
image = fetch_image(title, category, summary)
html_summary = mistune.html(summary).replace("&", "&").strip()
post = f"""
{html_summary}
Mindmap
If MindMap doesn't load, please try refreshing the page.
Citation
{citation_html}
"""
return post, image
def create_post(doi, title, category, summary, mindmap, citation):
try:
post_body, post_image = generate_post_html(doi, title, category, summary, mindmap, citation)
except Exception as e:
print(f"Error generating post: {e}")
return None, None, None, None
post_title = title.replace("&", "&")
if "&" in post_title:
return None, None, None, None
post_category = f"{category}"
return post_title, post_category, post_body, post_image
def fetch_oauth_token():
token_data = {
'grant_type': 'refresh_token',
'client_secret': CLIENT_SECRET,
'refresh_token': REFRESH_TOKEN,
'client_id': CLIENT_ID,
}
try:
response = requests.post('https://oauth2.googleapis.com/token', data=token_data)
response.raise_for_status()
token_info = response.json()
return token_info.get('access_token')
except Exception as e:
print(f"Error fetching OAuth token: {e}")
return None
def post_post(title, category, body, image):
access_token = fetch_oauth_token()
if not access_token:
return False
url = f"https://blogger.googleapis.com/v3/blogs/{BLOG_ID}/posts"
headers = {
'Authorization': f"Bearer {access_token}",
"Content-Type": "application/json"
}
post_data = {
"kind": "blogger#post",
"blog": {"id": BLOG_ID},
"images": [{"url": image}],
"title": title,
"content": body,
"labels": [category, "ZZZZZZZZZ"]
}
try:
response = requests.post(url, headers=headers, json=post_data)
response.raise_for_status()
result = response.json()
if result.get('status') == 'LIVE':
print(f"The post '{title}' is LIVE")
return True
else:
print(f"Error posting {title}: {result}")
return False
except Exception as e:
print(f"Error posting {title}: {e}")
return False
def post_blog(doi, title, category, summary, mindmap, citation, uaccess_key, wait_time=5):
if uaccess_key != ACCESS_KEY:
return False
post_title, post_category, post_body, post_image = create_post(doi, title, category, summary, mindmap, citation)
if not all([post_title, post_category, post_body, post_image]):
print(f"Failed to create post {post_title}")
return False
status = post_post(post_title, post_category, post_body, post_image)
print(f"Waiting for {wait_time * 60} seconds...")
time.sleep(wait_time * 60)
if status:
print("Post created successfully")
return True
else:
print("Failed to create post")
return False
if __name__ == "__main__":
doi = "https://doi.org/10.1234/example"
title = "Example Title"
category = "Science"
summary = "This is an example summary in markdown format."
mindmap = "{example: mindmap content}"
citation = "Example citation text"
uaccess_key = ACCESS_KEY
post_success = post_blog(doi, title, category, summary, mindmap, citation, uaccess_key)
print("Post success:", post_success)