-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup_google_apis.py
More file actions
263 lines (222 loc) Β· 9.21 KB
/
setup_google_apis.py
File metadata and controls
263 lines (222 loc) Β· 9.21 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
#!/usr/bin/env python3
"""
Setup script for Google API integration with ADHD Support System
Run this after downloading credentials.json from Google Cloud Console
"""
import os
import pickle
import json
from pathlib import Path
# Google API imports
try:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
print("β
Google API libraries installed")
except ImportError:
print("β Missing Google API libraries. Installing...")
os.system("pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client")
print("Please run this script again after installation completes")
exit(1)
# Define all scopes needed for ADHD support
SCOPES = [
# Calendar - Essential for meeting awareness
'https://www.googleapis.com/auth/calendar',
# Tasks - For ADHD task management
'https://www.googleapis.com/auth/tasks',
# Gmail - For email context (read-only)
'https://www.googleapis.com/auth/gmail.readonly',
# Drive - For document access (read-only)
'https://www.googleapis.com/auth/drive.readonly',
# Fitness - For activity tracking
'https://www.googleapis.com/auth/fitness.activity.read',
'https://www.googleapis.com/auth/fitness.sleep.read',
# Assistant SDK - For voice interactions
'https://www.googleapis.com/auth/assistant-sdk-prototype',
]
def authenticate_google_apis():
"""Authenticate and save tokens for all Google APIs."""
creds = None
token_file = 'token.pickle'
# Check for existing token
if os.path.exists(token_file):
with open(token_file, 'rb') as token:
creds = pickle.load(token)
print("π Loaded existing credentials")
# If there are no (valid) credentials available, let the user log in
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
print("π Refreshing expired credentials...")
creds.refresh(Request())
else:
if not os.path.exists('credentials.json'):
print("β credentials.json not found!")
print("\nPlease:")
print("1. Go to https://console.cloud.google.com/")
print("2. Create OAuth 2.0 credentials")
print("3. Download as credentials.json")
print("4. Place in this directory")
return False
print("π Starting OAuth flow...")
print("\nThis will open a browser for authentication.")
print("Please authorize access to the requested scopes.\n")
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
print("β
Authentication successful!")
# Save the credentials for the next run
with open(token_file, 'wb') as token:
pickle.dump(creds, token)
print("πΎ Saved credentials to token.pickle")
return creds
def test_apis(creds):
"""Test each API to ensure it's working."""
print("\nπ§ͺ Testing API connections...\n")
results = {}
# Test Calendar API
try:
service = build('calendar', 'v3', credentials=creds)
result = service.calendarList().list(maxResults=1).execute()
calendars = result.get('items', [])
if calendars:
print(f"β
Calendar API: Found calendar '{calendars[0]['summary']}'")
results['calendar'] = True
else:
print("β οΈ Calendar API: No calendars found")
results['calendar'] = False
except Exception as e:
print(f"β Calendar API: {e}")
results['calendar'] = False
# Test Tasks API
try:
service = build('tasks', 'v1', credentials=creds)
result = service.tasklists().list(maxResults=1).execute()
tasklists = result.get('items', [])
if tasklists:
print(f"β
Tasks API: Found task list '{tasklists[0]['title']}'")
results['tasks'] = True
else:
print("β οΈ Tasks API: No task lists found")
results['tasks'] = False
except Exception as e:
print(f"β Tasks API: {e}")
results['tasks'] = False
# Test Gmail API
try:
service = build('gmail', 'v1', credentials=creds)
result = service.users().labels().list(userId='me').execute()
labels = result.get('labels', [])
if labels:
print(f"β
Gmail API: Connected to inbox")
results['gmail'] = True
else:
print("β οΈ Gmail API: No labels found")
results['gmail'] = False
except Exception as e:
print(f"β Gmail API: {e}")
results['gmail'] = False
# Test Drive API
try:
service = build('drive', 'v3', credentials=creds)
result = service.files().list(pageSize=1).execute()
print(f"β
Drive API: Connected to Google Drive")
results['drive'] = True
except Exception as e:
print(f"β Drive API: {e}")
results['drive'] = False
# Test Fitness API
try:
service = build('fitness', 'v1', credentials=creds)
# This might fail if no fitness data exists
print(f"β
Fitness API: Connected (data may not be available)")
results['fitness'] = True
except Exception as e:
print(f"β οΈ Fitness API: {e}")
results['fitness'] = False
return results
def create_config_file(results):
"""Create configuration file for the ADHD system."""
config = {
"google_apis": {
"enabled": True,
"token_file": "token.pickle",
"credentials_file": "credentials.json",
"apis_available": results,
"scopes": SCOPES
},
"features": {
"calendar_integration": results.get('calendar', False),
"task_management": results.get('tasks', False),
"email_context": results.get('gmail', False),
"document_access": results.get('drive', False),
"fitness_tracking": results.get('fitness', False)
}
}
with open('google_api_config.json', 'w') as f:
json.dump(config, f, indent=2)
print("\nπ Created google_api_config.json")
return config
def setup_adhd_calendar(creds):
"""Create ADHD-specific calendar if it doesn't exist."""
try:
service = build('calendar', 'v3', credentials=creds)
# Check if ADHD Focus calendar exists
calendars = service.calendarList().list().execute()
adhd_calendar = None
for calendar in calendars.get('items', []):
if calendar['summary'] == 'ADHD Focus Time':
adhd_calendar = calendar
print(f"π
Found existing ADHD Focus Time calendar")
break
if not adhd_calendar:
# Create new calendar for ADHD focus sessions
calendar_body = {
'summary': 'ADHD Focus Time',
'description': 'Automated focus sessions and ADHD support events',
'timeZone': 'America/Los_Angeles' # Change to your timezone
}
adhd_calendar = service.calendars().insert(body=calendar_body).execute()
print(f"β
Created ADHD Focus Time calendar: {adhd_calendar['id']}")
return adhd_calendar['id']
except Exception as e:
print(f"β οΈ Could not create ADHD calendar: {e}")
return None
def main():
"""Main setup process."""
print("π§ ADHD Support System - Google API Setup")
print("=" * 50)
# Step 1: Authenticate
creds = authenticate_google_apis()
if not creds:
return
# Step 2: Test APIs
results = test_apis(creds)
# Step 3: Create config
config = create_config_file(results)
# Step 4: Setup ADHD calendar
if results.get('calendar'):
calendar_id = setup_adhd_calendar(creds)
if calendar_id:
config['adhd_calendar_id'] = calendar_id
with open('google_api_config.json', 'w') as f:
json.dump(config, f, indent=2)
# Summary
print("\n" + "=" * 50)
print("π Setup Summary:")
print(f"β
Authenticated: Yes")
print(f"π
Calendar API: {'β
' if results.get('calendar') else 'β'}")
print(f"π Tasks API: {'β
' if results.get('tasks') else 'β'}")
print(f"π§ Gmail API: {'β
' if results.get('gmail') else 'β'}")
print(f"π Drive API: {'β
' if results.get('drive') else 'β'}")
print(f"πͺ Fitness API: {'β
' if results.get('fitness') else 'β'}")
if all(results.values()):
print("\nπ All APIs configured successfully!")
else:
print("\nβ οΈ Some APIs need attention. Check the errors above.")
print("\nπ Next steps:")
print("1. The ADHD system will use token.pickle for authentication")
print("2. Your credentials are saved and will auto-refresh")
print("3. You can now use real calendar data instead of mocks")
if __name__ == "__main__":
main()