115 lines
4.0 KiB
Python
115 lines
4.0 KiB
Python
import caldav
|
|
import json
|
|
import requests
|
|
import tzdata
|
|
import sys
|
|
|
|
from loguru import logger
|
|
from datetime import datetime, timedelta
|
|
from zoneinfo import ZoneInfo
|
|
from urllib.parse import urlparse
|
|
from urllib.request import urlopen
|
|
import urllib.error
|
|
|
|
# Function to create calendar events from JSON data
|
|
def create_calendar_events_from_json(caldav_url, calendar_name, username, password, json, ra_user):
|
|
try:
|
|
# 1. Connect to CalDAV server
|
|
client = caldav.DAVClient(
|
|
url=caldav_url,
|
|
username=username,
|
|
password=password
|
|
)
|
|
|
|
# 2. Get principal and calendar
|
|
my_principal = client.principal()
|
|
my_calendar = my_principal.calendar(name=calendar_name) # Replace with your calendar name
|
|
|
|
# 3a. Read JSON data
|
|
response = requests.get(json)
|
|
response.raise_for_status()
|
|
|
|
# 3b. Parse JSON + Time Calculator
|
|
events_data = response.json()
|
|
|
|
# 3c. Convert UTC to PST
|
|
start_time = datetime.fromisoformat(events_data['StartAt']).replace(tzinfo=ZoneInfo('UTC')).astimezone(ZoneInfo('America/Los_Angeles'))
|
|
end_time = start_time + timedelta(weeks=1)
|
|
|
|
# 3d. Check if Username is on unlocks
|
|
status = "NEEDS-ACTION"
|
|
if "Unlocks" in events_data:
|
|
for unlock in events_data["Unlocks"]:
|
|
if unlock["User"] == "{ra_user}": # Replace with your username
|
|
status = "COMPLETED"
|
|
break
|
|
|
|
# 3e. Delete old data if it's the same.
|
|
for event in my_calendar.events():
|
|
if events_data['Achievement']['Title'] in event.data:
|
|
event.delete()
|
|
|
|
#print(f"Checking and removing duplicates...")
|
|
remaining = [e for e in my_calendar.events() if events_data['Achievement']['Title'] in e.data]
|
|
#print(f"Remaining duplicates: {len(remaining)}")
|
|
|
|
# 4. Create events from JSON data
|
|
logger.info("Updating calendar...")
|
|
ical_data_event = f"""BEGIN:VCALENDAR
|
|
VERSION:2.0
|
|
BEGIN:VEVENT
|
|
SUMMARY:{events_data['Achievement']['Title']}
|
|
DTSTART:{start_time.strftime('%Y%m%dT%H%M%S')}
|
|
DTEND:{end_time.strftime('%Y%m%dT%H%M%S')}
|
|
DESCRIPTION:{events_data['Achievement']['Description']}\\n\\nhttps://retroachievements.org/achievement/{events_data['Achievement']['ID']}
|
|
LOCATION:{events_data['Game']['Title']} for the {events_data['Console']['Title']}
|
|
CATEGORIES:RetroAchievements
|
|
END:VEVENT
|
|
END:VCALENDAR
|
|
"""
|
|
logger.info("Updating todos...")
|
|
ical_data_todo = f"""BEGIN:VCALENDAR
|
|
VERSION:2.0
|
|
BEGIN:VTODO
|
|
SUMMARY:{events_data['Achievement']['Title']}
|
|
DUE:{end_time.strftime('%Y%m%dT%H%M%S')}
|
|
STATUS:{status}
|
|
PRIORITY:1
|
|
DESCRIPTION:{events_data['Achievement']['Description']}\\n\\nhttps://retroachievements.org/achievement/{events_data['Achievement']['ID']}
|
|
LOCATION:{events_data['Game']['Title']} for the {events_data['Console']['Title']}
|
|
CATEGORIES:RetroAchievements
|
|
END:VTODO
|
|
END:VCALENDAR
|
|
"""
|
|
|
|
my_calendar.save_event(ical_data_event)
|
|
logger.info("Calendar updated.")
|
|
|
|
my_calendar.save_todo(ical_data_todo)
|
|
logger.info("Calendar updated.")
|
|
|
|
except Exception as e:
|
|
logger.exception("Error: {str(e)}")
|
|
|
|
# Usage example
|
|
if __name__ == "__main__":
|
|
logger.add("output_{time}.log", format="{name} {message}", level="DEBUG", rotation="5 MB", backtrace=True, colorize=True, diagnose=True)
|
|
|
|
if len(sys.argv) != 7:
|
|
logger.exception("Usage: python3 app.py <caldav_url> <calendar_name> <username> <password> <ra_api_key> [OPTIONAL] <ra_username>")
|
|
sys.exit(1)
|
|
|
|
CALDAV_URL = sys.argv[1]
|
|
CALENDAR_NAME = sys.argv[2]
|
|
USERNAME = sys.argv[3]
|
|
PASSWORD = sys.argv[4]
|
|
RA_API = sys.argv[5]
|
|
RA_USER = sys.argv[6]
|
|
|
|
# CalDAV server details
|
|
JSON = f"https://retroachievements.org/API/API_GetAchievementOfTheWeek.php?&y={RA_API}"
|
|
response = requests.get(JSON)
|
|
data = response.json()
|
|
|
|
create_calendar_events_from_json(CALDAV_URL, CALENDAR_NAME, USERNAME, PASSWORD, JSON, RA_USER)
|