-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1182 lines (969 loc) · 43 KB
/
app.py
File metadata and controls
1182 lines (969 loc) · 43 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from dotenv import load_dotenv
from cachetools import cached, TTLCache # NEW: Import for caching
from werkzeug.middleware.proxy_fix import ProxyFix
import secrets
import os
from google_auth_oauthlib.flow import Flow
from google.auth.transport.requests import Request
import json
# Load environment variables from a .env file before importing other modules
load_dotenv()
import llm_client
import calendar_client
import duration_feedback
import auth
from auth import login_required, get_current_user
from datetime import datetime, timedelta
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', secrets.token_urlsafe(32))
# Fix for running behind a proxy (Cloudflare Tunnel)
# This tells Flask to trust the X-Forwarded-* headers from the proxy
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
# OAuth Configuration
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # Allow HTTP for local development
GOOGLE_CLIENT_SECRETS_FILE = "credentials.json"
# Set preferred URL scheme for external URLs (fixes Cloudflare proxy issue)
app.config['PREFERRED_URL_SCHEME'] = 'https'
# NEW: Define a cache with max size 100 and TTL of 24 hours (86400 seconds) for daily updates
cache = TTLCache(maxsize=100, ttl=86400)
# NEW: Cached wrapper for fetching events (extended to 90 days for recurring events)
@cached(cache)
def get_cached_events():
print("Fetching fresh calendar events (cache miss)...")
return calendar_client.get_events_in_range(days_in_future=90)
def build_recurrence_rule(recurrence_obj):
"""
Converts a recurrence object from the LLM into Google Calendar RRULE format.
Args:
recurrence_obj: Dictionary with keys like frequency, interval, count, until, by_day
Returns:
List with single RRULE string, e.g., ['RRULE:FREQ=WEEKLY;COUNT=10;BYDAY=MO']
"""
if not recurrence_obj:
return None
frequency = recurrence_obj.get('frequency', 'WEEKLY').upper()
interval = recurrence_obj.get('interval', 1)
count = recurrence_obj.get('count')
until = recurrence_obj.get('until')
by_day = recurrence_obj.get('by_day', [])
# Build RRULE string
rrule_parts = [f"FREQ={frequency}"]
if interval > 1:
rrule_parts.append(f"INTERVAL={interval}")
# Use count OR until, not both (count takes precedence)
if count:
rrule_parts.append(f"COUNT={count}")
elif until:
# Convert until date to RRULE format (YYYYMMDD)
try:
until_dt = datetime.fromisoformat(until)
until_formatted = until_dt.strftime("%Y%m%d")
rrule_parts.append(f"UNTIL={until_formatted}T235959Z")
except ValueError:
# If date parsing fails, default to 10 occurrences
rrule_parts.append("COUNT=10")
else:
# Default to 10 occurrences if neither count nor until specified
rrule_parts.append("COUNT=10")
# Add day of week for weekly recurrence
if frequency == 'WEEKLY' and by_day:
by_day_str = ",".join(by_day)
rrule_parts.append(f"BYDAY={by_day_str}")
rrule = "RRULE:" + ";".join(rrule_parts)
return [rrule]
# Authentication Routes
@app.route('/login', methods=['GET', 'POST'])
def login():
"""
Login page and handler
"""
if request.method == 'GET':
return render_template('login.html')
data = request.form
email = data.get('email')
password = data.get('password')
remember = data.get('remember') == 'true'
if not email or not password:
return render_template('login.html', error='Email and password are required')
user = auth.verify_user(email, password)
if not user:
return render_template('login.html', error='Invalid email or password')
# Create session
session_token, expiry = auth.create_session(email, remember_me=remember)
session['session_token'] = session_token
return redirect(url_for('index'))
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
Registration page and handler
"""
if request.method == 'GET':
return render_template('register.html')
data = request.form
email = data.get('email')
password = data.get('password')
confirm_password = data.get('confirm_password')
if not email or not password:
return render_template('register.html', error='Email and password are required')
if password != confirm_password:
return render_template('register.html', error='Passwords do not match')
if len(password) < 8:
return render_template('register.html', error='Password must be at least 8 characters')
# Create user
user = auth.create_user(email, password)
if not user:
return render_template('register.html', error='Email already registered')
return render_template('register.html', success='Account created! Please log in.')
@app.route('/logout')
def logout():
"""
Logout handler
"""
session_token = session.get('session_token')
if session_token:
auth.delete_session(session_token)
session.pop('session_token', None)
return redirect(url_for('login'))
@app.route('/auth/google')
def google_auth():
"""
Initiate Google OAuth flow
"""
try:
# Define scopes for user authentication AND calendar access
scopes = [
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/calendar' # Add calendar access
]
# Generate redirect URI
redirect_uri = url_for('google_callback', _external=True)
print(f"🔍 DEBUG: Generated redirect_uri: {redirect_uri}")
print(f"🔍 DEBUG: Request URL: {request.url}")
print(f"🔍 DEBUG: Request host: {request.host}")
print(f"🔍 DEBUG: Scopes: {scopes}")
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow
flow = Flow.from_client_secrets_file(
GOOGLE_CLIENT_SECRETS_FILE,
scopes=scopes,
redirect_uri=redirect_uri
)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='false', # Changed to false to prevent scope conflicts
prompt='consent' # Force re-consent to get refresh_token
)
# Store the state and scopes in session to verify the callback
session['oauth_state'] = state
session['oauth_scopes'] = scopes
return redirect(authorization_url)
except Exception as e:
print(f"OAuth error: {e}")
return render_template('login.html', error=f'OAuth configuration error. Please ensure credentials.json is set up correctly.')
@app.route('/auth/google/callback')
def google_callback():
"""
Handle Google OAuth callback
"""
try:
# Verify state to prevent CSRF attacks
state = session.get('oauth_state')
if not state:
return render_template('login.html', error='Invalid OAuth state')
# Get the scopes from session to ensure consistency
scopes = session.get('oauth_scopes', [
'openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/calendar'
])
print(f"🔍 DEBUG Callback - State: {state}")
print(f"🔍 DEBUG Callback - Scopes: {scopes}")
print(f"🔍 DEBUG Callback - Request URL: {request.url}")
# Create flow instance with the same configuration
flow = Flow.from_client_secrets_file(
GOOGLE_CLIENT_SECRETS_FILE,
scopes=scopes,
state=state,
redirect_uri=url_for('google_callback', _external=True)
)
# Fetch the token using the authorization response
flow.fetch_token(authorization_response=request.url)
# Get credentials and user info
credentials = flow.credentials
# Use the credentials to get user info
import google.auth.transport.requests
import requests as http_requests
user_info_response = http_requests.get(
'https://www.googleapis.com/oauth2/v2/userinfo',
headers={'Authorization': f'Bearer {credentials.token}'}
)
if user_info_response.status_code != 200:
return render_template('login.html', error='Failed to get user information from Google')
user_info = user_info_response.json()
email = user_info.get('email')
if not email:
return render_template('login.html', error='Could not retrieve email from Google account')
# Save calendar credentials to token.json for calendar_client.py to use
with open('token.json', 'w') as token_file:
token_file.write(credentials.to_json())
print(f"✅ Saved calendar credentials to token.json")
# Check if user exists, if not create them
users = auth.load_users()
if email not in users:
# Create user with OAuth provider
# Generate a random password since they'll login via OAuth
random_password = secrets.token_urlsafe(32)
user = auth.create_user(email, random_password, oauth_provider='google')
else:
# Update existing user to mark OAuth provider
users[email]['oauth_provider'] = 'google'
auth.save_users(users)
# Create session
session_token, expiry = auth.create_session(email, remember_me=True) # OAuth users get 30-day sessions
session['session_token'] = session_token
# Clear OAuth state and scopes to prevent conflicts
session.pop('oauth_state', None)
session.pop('oauth_scopes', None)
print(f"✅ OAuth successful for: {email}")
return redirect(url_for('index'))
except Exception as e:
print(f"❌ OAuth callback error: {e}")
import traceback
traceback.print_exc()
return render_template('login.html', error=f'Authentication failed: {str(e)}')
@app.route('/')
@login_required
def index():
"""
Serves the main HTML dashboard.
"""
user = get_current_user()
return render_template('index.html', user=user)
@app.route('/check_recurring', methods=['POST'])
@login_required
def check_recurring():
"""
Analyzes text to detect if it's a recurring event request.
Returns suggested recurrence pattern for user confirmation.
"""
data = request.get_json()
text_input = data.get('text', '').lower()
# Check for recurring keywords
recurring_keywords = ['every', 'weekly', 'daily', 'monthly', 'bi-weekly', 'recurring']
is_recurring = any(keyword in text_input for keyword in recurring_keywords)
if not is_recurring:
return jsonify({"is_recurring": False})
# Try to detect pattern using simple rules
pattern = {
"is_recurring": True,
"frequency": "WEEKLY",
"count": 10,
"by_day": []
}
# Detect frequency
if 'daily' in text_input or 'every day' in text_input:
pattern["frequency"] = "DAILY"
elif 'monthly' in text_input:
pattern["frequency"] = "MONTHLY"
elif 'yearly' in text_input or 'annual' in text_input:
pattern["frequency"] = "YEARLY"
# Detect interval
if 'bi-weekly' in text_input or 'every other week' in text_input or 'every 2 weeks' in text_input:
pattern["frequency"] = "WEEKLY"
pattern["interval"] = 2
# Detect days of week
days_map = {
'monday': 'MO', 'tuesday': 'TU', 'wednesday': 'WE',
'thursday': 'TH', 'friday': 'FR', 'saturday': 'SA', 'sunday': 'SU'
}
for day_name, day_code in days_map.items():
if day_name in text_input:
pattern["by_day"].append(day_code)
# Detect count/duration
import re
# Look for "for X weeks/months/days"
count_match = re.search(r'for (\d+) (week|month|day)', text_input)
if count_match:
number = int(count_match.group(1))
unit = count_match.group(2)
if unit == 'week' and pattern["frequency"] == "WEEKLY":
pattern["count"] = number
elif unit == 'month':
if pattern["frequency"] == "WEEKLY":
pattern["count"] = number * 4 # Approximate weeks per month
elif pattern["frequency"] == "MONTHLY":
pattern["count"] = number
elif unit == 'day' and pattern["frequency"] == "DAILY":
pattern["count"] = number
# Look for "X times"
times_match = re.search(r'(\d+) times', text_input)
if times_match:
pattern["count"] = int(times_match.group(1))
return jsonify(pattern)
@app.route('/schedule', methods=['POST'])
@login_required
def schedule():
"""
Receives a high-level task, generates a study plan, and schedules multiple events.
Supports recurring events with user-confirmed recurrence parameters.
"""
data = request.get_json()
text_input = data.get('text')
user_recurrence = data.get('recurrence') # User-confirmed recurrence from popup
if not text_input:
return jsonify({"error": "No text provided"}), 400
# 1. Fetch calendar context (extended to 90 days for recurring events)
print("Fetching calendar events to provide context to the planner...")
upcoming_events = calendar_client.get_events_in_range(days_in_future=90)
# 2. Call the AI planner to generate a study plan
print("Sending request to the AI planner...")
new_events_plan = llm_client.generate_study_plan(text_input, upcoming_events)
if not new_events_plan:
return jsonify({"error": "The AI planner could not create a plan from your request."}), 500
# 3. Loop through the plan and create events
created_count = 0
conflicts_detected = []
for event_details in new_events_plan:
summary = event_details.get("summary")
start_time = event_details.get("start_time")
end_time = event_details.get("end_time")
if not all([summary, start_time, end_time]):
print(f"Skipping malformed event from LLM: {event_details}")
continue
# Validate and sanitize the data from the LLM before creating the event
try:
from datetime import datetime, timedelta
start_time_dt = datetime.fromisoformat(start_time)
end_time_dt = datetime.fromisoformat(end_time)
# Ensure timezone awareness
if start_time_dt.tzinfo is None:
start_time_dt = start_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
start_time = start_time_dt.isoformat()
if end_time_dt.tzinfo is None:
end_time_dt = end_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
end_time = end_time_dt.isoformat()
if end_time_dt <= start_time_dt:
end_time_dt = start_time_dt + timedelta(hours=1)
end_time = end_time_dt.isoformat()
except ValueError:
print(f"Skipping event with invalid timestamp from LLM: {event_details}")
continue
# Enhanced conflict detection
conflicts = detect_conflicts(start_time_dt, end_time_dt, upcoming_events)
if conflicts:
# Store conflict information for user resolution
conflict_info = {
'proposed_event': {
'summary': summary,
'start_time': start_time,
'end_time': end_time
},
'conflicts': conflicts
}
conflicts_detected.append(conflict_info)
print(f"Conflict detected for event: {summary}")
continue
# Check if this is a recurring event
# Priority: user_recurrence (from popup) > event_details recurrence (from LLM)
recurrence_rules = None
if user_recurrence:
recurrence_rules = build_recurrence_rule(user_recurrence)
elif 'recurrence' in event_details:
recurrence_rules = build_recurrence_rule(event_details['recurrence'])
# Create the event if no conflicts
created_event = calendar_client.create_event(summary, start_time, end_time, recurrence=recurrence_rules)
if created_event:
created_count += 1
# Return response with conflict information if any
if conflicts_detected:
return jsonify({
"conflicts": conflicts_detected,
"created_count": created_count,
"message": f"Successfully scheduled {created_count} event(s). {len(conflicts_detected)} conflict(s) detected."
}), 409 # 409 Conflict status code
elif created_count > 0:
return jsonify({"message": f"Successfully scheduled {created_count} new event(s)!"})
else:
return jsonify({"error": "AI created a plan, but failed to schedule any events."}), 500
def detect_conflicts(new_start_dt, new_end_dt, existing_events):
"""
Enhanced conflict detection that returns detailed conflict information.
"""
conflicts = []
# Ensure new event times are timezone-aware
if new_start_dt.tzinfo is None:
new_start_dt = new_start_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
if new_end_dt.tzinfo is None:
new_end_dt = new_end_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
for existing in existing_events:
existing_start = existing.get('start', {}).get('dateTime') or existing.get('start', {}).get('date')
existing_end = existing.get('end', {}).get('dateTime') or existing.get('end', {}).get('date')
if existing_start and existing_end:
try:
existing_start_dt = datetime.fromisoformat(existing_start)
existing_end_dt = datetime.fromisoformat(existing_end)
# Ensure existing event times are timezone-aware
if existing_start_dt.tzinfo is None:
existing_start_dt = existing_start_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
if existing_end_dt.tzinfo is None:
existing_end_dt = existing_end_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
# Convert all times to the same timezone for comparison
if new_start_dt.tzinfo != existing_start_dt.tzinfo:
existing_start_dt = existing_start_dt.astimezone(new_start_dt.tzinfo)
existing_end_dt = existing_end_dt.astimezone(new_end_dt.tzinfo)
# Check for overlap
if (new_start_dt < existing_end_dt and new_end_dt > existing_start_dt):
# Calculate overlap duration
overlap_start = max(new_start_dt, existing_start_dt)
overlap_end = min(new_end_dt, existing_end_dt)
overlap_minutes = (overlap_end - overlap_start).total_seconds() / 60
conflict = {
'existing_event': {
'summary': existing.get('summary', 'Untitled Event'),
'start_time': existing_start,
'end_time': existing_end,
'id': existing.get('id')
},
'overlap_minutes': int(overlap_minutes),
'severity': 'high' if overlap_minutes > 30 else 'low'
}
conflicts.append(conflict)
except ValueError as e:
print(f"Error parsing datetime in conflict detection: {e}")
continue
return conflicts
@app.route('/force_schedule', methods=['POST'])
@login_required
def force_schedule():
"""
Force schedule an event even if conflicts exist (user override).
"""
data = request.get_json()
event_data = data.get('event')
if not event_data:
return jsonify({"error": "No event data provided"}), 400
summary = event_data.get('summary')
start_time = event_data.get('start_time')
end_time = event_data.get('end_time')
if not all([summary, start_time, end_time]):
return jsonify({"error": "Missing event details"}), 400
# Create the event without conflict checking
created_event = calendar_client.create_event(summary, start_time, end_time)
if created_event:
return jsonify({"message": f"Event '{summary}' scheduled successfully (conflicts overridden)!"})
else:
return jsonify({"error": "Failed to create event"}), 500
@app.route('/get_alternatives', methods=['POST'])
@login_required
def get_alternatives():
"""
Get AI-generated alternative times for a conflicting event.
"""
data = request.get_json()
proposed_event = data.get('proposed_event')
conflicts = data.get('conflicts', [])
if not proposed_event:
return jsonify({"error": "No proposed event provided"}), 400
# Get fresh calendar events for context
upcoming_events = get_cached_events()
# Use LLM to suggest alternatives
alternatives = llm_client.suggest_alternative_times(
proposed_event,
conflicts,
upcoming_events
)
return jsonify({"alternatives": alternatives})
@app.route('/schedule_alternative', methods=['POST'])
@login_required
def schedule_alternative():
"""
Schedule an event at one of the suggested alternative times.
"""
data = request.get_json()
summary = data.get('summary')
start_time = data.get('start_time')
end_time = data.get('end_time')
if not all([summary, start_time, end_time]):
return jsonify({"error": "Missing event details"}), 400
# Validate the alternative time doesn't have conflicts
try:
from datetime import datetime
start_time_dt = datetime.fromisoformat(start_time)
end_time_dt = datetime.fromisoformat(end_time)
# Ensure timezone awareness
if start_time_dt.tzinfo is None:
start_time_dt = start_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
start_time = start_time_dt.isoformat()
if end_time_dt.tzinfo is None:
end_time_dt = end_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
end_time = end_time_dt.isoformat()
# Double-check for conflicts with current calendar
upcoming_events = get_cached_events()
conflicts = detect_conflicts(start_time_dt, end_time_dt, upcoming_events)
if conflicts:
return jsonify({
"error": "The suggested alternative time now has conflicts. Please try another option.",
"conflicts": conflicts
}), 409
except ValueError:
return jsonify({"error": "Invalid datetime format"}), 400
# Create the event at the alternative time
created_event = calendar_client.create_event(summary, start_time, end_time)
if created_event:
return jsonify({"message": f"Event '{summary}' scheduled successfully at alternative time!"})
else:
return jsonify({"error": "Failed to create event"}), 500
@app.route('/move_existing_event', methods=['POST'])
@login_required
def move_existing_event():
"""
Move an existing event to a new time and schedule the new event at the original time.
"""
data = request.get_json()
existing_event_id = data.get('existing_event_id')
new_start_time = data.get('new_start_time')
new_end_time = data.get('new_end_time')
proposed_event = data.get('proposed_event')
if not all([existing_event_id, new_start_time, new_end_time, proposed_event]):
return jsonify({"error": "Missing required details"}), 400
try:
# Validate the new time for existing event doesn't conflict
from datetime import datetime
start_time_dt = datetime.fromisoformat(new_start_time)
end_time_dt = datetime.fromisoformat(new_end_time)
# Ensure timezone awareness
if start_time_dt.tzinfo is None:
start_time_dt = start_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
new_start_time = start_time_dt.isoformat()
if end_time_dt.tzinfo is None:
end_time_dt = end_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
new_end_time = end_time_dt.isoformat()
# Check for conflicts with the new time for existing event
upcoming_events = get_cached_events()
conflicts = detect_conflicts(start_time_dt, end_time_dt, upcoming_events)
# Filter out the event we're moving from conflicts
conflicts = [c for c in conflicts if c['existing_event']['id'] != existing_event_id]
if conflicts:
return jsonify({
"error": "The suggested time for moving the existing event now has conflicts.",
"conflicts": conflicts
}), 409
# Move the existing event
moved_event = calendar_client.update_event(
existing_event_id,
new_start_time,
new_end_time
)
if not moved_event:
return jsonify({"error": "Failed to move existing event"}), 500
# Schedule the new event at the original requested time
created_event = calendar_client.create_event(
proposed_event['summary'],
proposed_event['start_time'],
proposed_event['end_time']
)
if created_event:
return jsonify({
"message": f"Successfully moved existing event and scheduled '{proposed_event['summary']}' at your requested time!"
})
else:
# If new event fails, try to restore the original event
calendar_client.update_event(
existing_event_id,
proposed_event['start_time'], # Restore to original time
proposed_event['end_time']
)
return jsonify({"error": "Failed to create new event. Existing event restored."}), 500
except ValueError:
return jsonify({"error": "Invalid datetime format"}), 400
@app.route('/suggest_split', methods=['POST'])
@login_required
def suggest_split():
"""
Suggests how to split a task into smaller blocks if needed.
"""
data = request.get_json()
proposed_event = data.get('proposed_event')
if not proposed_event:
return jsonify({"error": "No event data provided"}), 400
# Get calendar context
upcoming_events = get_cached_events()
# Get AI suggestion for splitting
split_suggestion = llm_client.suggest_task_split(proposed_event, upcoming_events)
return jsonify(split_suggestion)
@app.route('/schedule_split', methods=['POST'])
@login_required
def schedule_split():
"""
Schedules a task as multiple split blocks.
"""
data = request.get_json()
split_events = data.get('events')
if not split_events or not isinstance(split_events, list):
return jsonify({"error": "Invalid split events data"}), 400
created_count = 0
failed_events = []
upcoming_events = get_cached_events()
for event_data in split_events:
summary = event_data.get('summary')
start_time = event_data.get('start_time')
end_time = event_data.get('end_time')
if not all([summary, start_time, end_time]):
failed_events.append({"event": event_data, "reason": "Missing required fields"})
continue
try:
from datetime import datetime
start_time_dt = datetime.fromisoformat(start_time)
end_time_dt = datetime.fromisoformat(end_time)
# Ensure timezone awareness
if start_time_dt.tzinfo is None:
start_time_dt = start_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
start_time = start_time_dt.isoformat()
if end_time_dt.tzinfo is None:
end_time_dt = end_time_dt.replace(tzinfo=datetime.now().astimezone().tzinfo)
end_time = end_time_dt.isoformat()
# Check for conflicts
conflicts = detect_conflicts(start_time_dt, end_time_dt, upcoming_events)
if conflicts:
failed_events.append({
"event": event_data,
"reason": "Conflicts detected",
"conflicts": conflicts
})
continue
# Create the event
created_event = calendar_client.create_event(summary, start_time, end_time)
if created_event:
created_count += 1
else:
failed_events.append({"event": event_data, "reason": "Failed to create event"})
except ValueError as e:
failed_events.append({"event": event_data, "reason": f"Invalid datetime: {str(e)}"})
if failed_events:
return jsonify({
"message": f"Scheduled {created_count} of {len(split_events)} events",
"created_count": created_count,
"failed_events": failed_events
}), 207 # Multi-Status
else:
return jsonify({
"message": f"Successfully scheduled all {created_count} split events!",
"created_count": created_count
})
@app.route('/tasks', methods=['GET'])
@login_required
def get_tasks():
"""
Fetches today's events from Google Calendar and returns them as a list.
"""
events = calendar_client.get_daily_events()
tasks = []
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
# Format the time nicely for display
try:
# For dateTime events
time_formatted = datetime.fromisoformat(start).strftime('%I:%M %p')
except ValueError:
# For all-day events
time_formatted = "All Day"
tasks.append({
"summary": event['summary'],
"start_time": time_formatted
})
return jsonify(tasks)
@app.route('/events', methods=['GET'])
@login_required
def get_events():
"""
Fetches events for calendar view (next 30 days) and returns them in FullCalendar format.
"""
events = get_cached_events()
calendar_events = []
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date'))
# Convert to FullCalendar format
calendar_event = {
'id': event.get('id'),
'title': event.get('summary', 'No Title'),
'start': start,
'end': end,
'allDay': 'date' in event['start'] # True if it's a date-only event
}
calendar_events.append(calendar_event)
return jsonify(calendar_events)
@app.route('/feedback/duration', methods=['POST'])
@login_required
def add_duration_feedback():
"""
Add feedback about typical duration for assignments.
Supports both class-specific and general assignment type feedback.
"""
data = request.get_json()
feedback_type = data.get('type') # 'class_specific' or 'general' or 'freeform'
if feedback_type == 'class_specific':
class_name = data.get('class_name')
assignment_type = data.get('assignment_type')
duration_hours = data.get('duration_hours')
notes = data.get('notes', '')
if not all([class_name, assignment_type, duration_hours]):
return jsonify({"error": "Missing required fields: class_name, assignment_type, duration_hours"}), 400
try:
duration_hours = float(duration_hours)
feedback = duration_feedback.add_class_duration_feedback(
class_name, assignment_type, duration_hours, notes
)
return jsonify({
"message": f"Learned: {class_name} {assignment_type} typically takes {duration_hours} hours",
"feedback": feedback
})
except ValueError:
return jsonify({"error": "duration_hours must be a number"}), 400
elif feedback_type == 'general':
assignment_type = data.get('assignment_type')
duration_hours = data.get('duration_hours')
notes = data.get('notes', '')
if not all([assignment_type, duration_hours]):
return jsonify({"error": "Missing required fields: assignment_type, duration_hours"}), 400
try:
duration_hours = float(duration_hours)
feedback = duration_feedback.add_general_assignment_feedback(
assignment_type, duration_hours, notes
)
return jsonify({
"message": f"Learned: {assignment_type} typically takes {duration_hours} hours",
"feedback": feedback
})
except ValueError:
return jsonify({"error": "duration_hours must be a number"}), 400
elif feedback_type == 'freeform':
feedback_text = data.get('feedback_text')
if not feedback_text:
return jsonify({"error": "Missing required field: feedback_text"}), 400
feedback = duration_feedback.add_freeform_feedback(feedback_text)
return jsonify({
"message": "Feedback recorded successfully",
"feedback": feedback
})
else:
return jsonify({"error": "Invalid feedback type. Use 'class_specific', 'general', or 'freeform'"}), 400
@app.route('/feedback/smart', methods=['POST'])
@login_required
def add_smart_feedback():
"""
Smart feedback endpoint that tries to parse natural language feedback.
Example: "ECEN 380 homework always takes 4-5 hours"
"""
data = request.get_json()
feedback_text = data.get('feedback_text')
if not feedback_text:
return jsonify({"error": "Missing required field: feedback_text"}), 400
# Try to extract structured information
class_name = duration_feedback.extract_class_from_text(feedback_text)
assignment_type = duration_feedback.extract_assignment_type(feedback_text)
# Try to extract duration (look for numbers followed by 'hour' or 'hr')
import re
duration_pattern = r'(\d+(?:\.\d+)?)\s*(?:-\s*(\d+(?:\.\d+)?))?\s*(?:hour|hr)'
duration_match = re.search(duration_pattern, feedback_text.lower())
if duration_match:
duration_start = float(duration_match.group(1))
duration_end = float(duration_match.group(2)) if duration_match.group(2) else duration_start
duration_hours = (duration_start + duration_end) / 2 # Use average
if class_name and assignment_type:
# Class-specific feedback
feedback = duration_feedback.add_class_duration_feedback(
class_name, assignment_type, duration_hours, feedback_text
)
return jsonify({
"message": f"✓ Learned: {class_name} {assignment_type} typically takes {duration_hours} hours",
"extracted": {
"class_name": class_name,
"assignment_type": assignment_type,
"duration_hours": duration_hours
},
"feedback": feedback
})
elif assignment_type:
# General assignment type feedback
feedback = duration_feedback.add_general_assignment_feedback(
assignment_type, duration_hours, feedback_text
)
return jsonify({
"message": f"✓ Learned: {assignment_type} typically takes {duration_hours} hours",
"extracted": {
"assignment_type": assignment_type,
"duration_hours": duration_hours
},
"feedback": feedback
})
# If we couldn't extract structured data, save as freeform
feedback = duration_feedback.add_freeform_feedback(feedback_text)
return jsonify({
"message": "✓ Feedback recorded. I'll try to learn from this preference.",
"note": "Could not extract specific class/duration info, saved as general feedback",
"feedback": feedback
})
@app.route('/feedback/view', methods=['GET'])
@login_required
def view_feedback():
"""
View all learned feedback patterns.
"""
feedback = duration_feedback.load_feedback()
summary = duration_feedback.get_feedback_summary()
return jsonify({
"summary": summary,
"raw_data": feedback