-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_ical_lambda.py
More file actions
182 lines (155 loc) · 6.45 KB
/
create_ical_lambda.py
File metadata and controls
182 lines (155 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import pandas as pd
from icalendar import Calendar, Event
from datetime import datetime, timedelta
import pytz
import requests
from io import StringIO
import boto3
import json
from botocore.exceptions import NoCredentialsError
# AWS S3 Configuration
S3_BUCKET_NAME = "e-cal"
S3_OBJECT_NAME = "calendar.ics"
CACHE_FILE_NAME = "image_cache.json"
# Initialize S3 client
s3_client = boto3.client('s3')
# Load cache from S3
def load_cache_from_s3(bucket_name, cache_file_name):
try:
response = s3_client.get_object(Bucket=bucket_name, Key=cache_file_name)
cache = json.loads(response['Body'].read().decode('utf-8'))
print("Cache loaded from S3.")
return cache
except s3_client.exceptions.NoSuchKey:
print("Cache file not found in S3. Starting with an empty cache.")
return {}
except Exception as e:
print(f"Error loading cache from S3: {e}")
return {}
# Save cache to S3
def save_cache_to_s3(bucket_name, cache_file_name, cache):
try:
s3_client.put_object(
Bucket=bucket_name,
Key=cache_file_name,
Body=json.dumps(cache),
ContentType="application/json"
)
print("Cache saved to S3.")
except Exception as e:
print(f"Error saving cache to S3: {e}")
# Fetch data from Google Sheets
def fetch_google_sheet_data(url):
try:
response = requests.get(url)
if response.status_code == 200:
data = StringIO(response.content.decode('utf-8'))
return pd.read_csv(data)
else:
raise Exception(f"Failed to fetch data from Google Sheets. Status code: {response.status_code}")
except Exception as e:
print(f"Error fetching Google Sheets data: {e}")
raise
# Correctly parse date from DD/MM/YYYY format
def parse_date(date_string):
return datetime.strptime(date_string, "%d/%m/%Y").date()
# Combine date and time
def combine_datetime(date, time_value):
if pd.isnull(date) or pd.isnull(time_value):
raise ValueError("Date or time is missing.")
parsed_date = parse_date(date)
parsed_time = datetime.strptime(time_value, "%H:%M").time()
return datetime.combine(parsed_date, parsed_time).astimezone(pytz.UTC)
# Create the iCalendar file
def create_ical(df, output_file, calendar_name, cache):
cal = Calendar()
cal.add('prodid', '-//Guy Bashan Auto Tools//EN')
cal.add('version', '2.0')
cal.add('X-WR-CALNAME', calendar_name)
cal.add('X-APPLE-CALENDAR-COLOR', '#32CD32')
# Get today's date in UTC
today_utc = datetime.utcnow().date()
three_days_ago = today_utc - timedelta(days=3)
for _, row in df.iterrows():
try:
event_date = parse_date(row['תאריך'])
except Exception:
continue # Skip event if the date is invalid
# Skip events that happened more than 3 days ago
if event_date < three_days_ago:
continue
event = Event()
try:
start_dt = combine_datetime(row['תאריך'], row['שעה'])
end_dt = combine_datetime(row['תאריך'], row['סיום'])
except Exception:
start_dt = None
end_dt = None
if start_dt and end_dt:
event.add('dtstart', start_dt)
event.add('dtend', end_dt)
else:
event.add('dtstart', event_date)
event.add('dtend', event_date + timedelta(days=1))
event.add('summary', row['אירוע'])
# Add description with additional details and URL
description = ""
if 'שעה' in row and pd.notnull(row['שעה']):
description += f"שעה: {row['שעה']}\n"
if 'גיל' in row and pd.notnull(row['גיל']):
description += f"גילאים: {row['גיל']}\n" # Mapping גיל -> גילאים
if 'עלות' in row and pd.notnull(row['עלות']):
description += f"עלות: {row['עלות']}\n"
if 'מפיק' in row and pd.notnull(row['מפיק']):
description += f"הפקה: {row['מפיק']}\n"
if 'לינק' in row and pd.notnull(row['לינק']):
description += f"לפרטים נוספים: {row['לינק']}"
event.add('description', description)
event.add('location', row.get('מיקום', ''))
event.add('dtstamp', datetime.now(pytz.UTC))
event['uid'] = f"{datetime.now().timestamp()}@your-calendar.com"
cal.add_component(event)
with open(output_file, 'wb') as f:
f.write(cal.to_ical())
# Upload to S3
def upload_to_s3(file_path, bucket_name, object_name):
try:
s3_client.upload_file(
Filename=file_path,
Bucket=bucket_name,
Key=object_name,
ExtraArgs={
"ContentType": "text/calendar", # Set the correct MIME type
"CacheControl": "max-age=3600, must-revalidate" # Add Cache-Control header
}
)
print(f"Success: Uploaded {file_path} to s3://{bucket_name}/{object_name}")
except Exception as e:
print(f"Error: Failed to upload {file_path} to s3://{bucket_name}/{object_name}: {e}")
# Main Lambda handler
def lambda_handler(event, context):
cache = load_cache_from_s3(S3_BUCKET_NAME, CACHE_FILE_NAME)
try:
df = fetch_google_sheet_data("https://docs.google.com/spreadsheets/d/1N2Vlb87anEW8luoAxkKtVg2Qg4lbYQd4hrCBFEex6pI/export?format=csv&gid=1975579683")
# Normalize column names
df.columns = df.columns.str.encode('utf-8').str.decode('utf-8')
df.rename(columns={
'אירוע': 'אירוע',
'תאריך': 'תאריך',
'שעה': 'שעה',
'סיום': 'סיום',
'תיאור': 'תיאור',
'מיקום': 'מיקום',
'לינק': 'לינק',
'גיל': 'גיל', # Keeping גיל here since it's mapped later
'עלות': 'עלות',
'מפיק': 'מפיק' # Adding מפיק for production name
}, inplace=True)
ics_output_path = "/tmp/calendar.ics"
create_ical(df, ics_output_path, "מסיבות טראנס", cache)
upload_to_s3(ics_output_path, S3_BUCKET_NAME, S3_OBJECT_NAME)
save_cache_to_s3(S3_BUCKET_NAME, CACHE_FILE_NAME, cache)
return {"statusCode": 200, "body": "Calendar file created and uploaded successfully."}
except Exception as e:
print(f"Error: {e}")
return {"statusCode": 500, "body": f"Error: {str(e)}"}