Skip to content

Commit

Permalink
Process existing ics files from URL
Browse files Browse the repository at this point in the history
  • Loading branch information
melissawm committed Oct 21, 2023
1 parent 2dd77b4 commit 984bde2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ dependencies = [
"ics == 0.8.0.dev0",
"python-dateutil >= 2.8",
"pyyaml >= 6",
"requests",
]

[project.optional-dependencies]
Expand Down
30 changes: 21 additions & 9 deletions yaml2ics.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import dateutil.rrule
import ics
import yaml
import requests
from dateutil.tz import gettz

interval_type = {
Expand Down Expand Up @@ -146,7 +147,7 @@ def events_to_calendar(events: list) -> str:
return cal


def files_to_events(files: list) -> (ics.Calendar, str):
def files_to_events(files: list) -> (ics.Calendar, str, bool):
"""Process files to a list of events"""
all_events = []
name = None
Expand All @@ -156,6 +157,14 @@ def files_to_events(files: list) -> (ics.Calendar, str):
calendar_yaml = yaml.load(f.read(), Loader=yaml.FullLoader)
else:
calendar_yaml = yaml.load(open(f), Loader=yaml.FullLoader)

external = calendar_yaml.get("ics", None)
if external is not None:
# This is an existing ics file that we have to download
name = calendar_yaml.get("name", name)
all_events = requests.get(external).text
return all_events, name, True

tz = calendar_yaml.get("timezone", None)
if tz is not None:
tz = gettz(tz)
Expand All @@ -172,19 +181,23 @@ def files_to_events(files: list) -> (ics.Calendar, str):
# keep the last one we find
name = calendar_yaml.get("name", name)

return all_events, name
return all_events, name, False


def files_to_calendar(files: list) -> ics.Calendar:
"""'main function: list of files to our result"""
all_events, name = files_to_events(files)
all_events, name, is_external = files_to_events(files)

calendar = events_to_calendar(all_events)
if name is not None:
calendar.extra.append(ics.ContentLine(name="NAME", value=name))
calendar.extra.append(ics.ContentLine(name="X-WR-CALNAME", value=name))
return calendar
if is_external:
# Existing external ics file
calendar = ics.Calendar(all_events)
else:
calendar = events_to_calendar(all_events)
if name is not None:
calendar.extra.append(ics.ContentLine(name="NAME", value=name))
calendar.extra.append(ics.ContentLine(name="X-WR-CALNAME", value=name))

return calendar

# `main` is separate from `cli` to facilitate testing.
# The only difference being that `main` raises errors while
Expand All @@ -199,7 +212,6 @@ def main():
raise RuntimeError(f"Error: {f} is not a file")

calendar = files_to_calendar(files)

print(calendar.serialize())


Expand Down

0 comments on commit 984bde2

Please sign in to comment.