Class: Gcal::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/utilities/gcal/service.rb

Constant Summary collapse

SCOPES =
[
  "https://www.googleapis.com/auth/calendar.readonly",
  "https://www.googleapis.com/auth/drive.readonly"
]
SCOPE =
SCOPES.join(" ")

Instance Method Summary collapse

Constructor Details

#initialize(skip_auth: false) ⇒ Service

Returns a new instance of Service.



21
22
23
24
25
# File 'lib/utilities/gcal/service.rb', line 21

def initialize(skip_auth: false)
  ensure_env!
  @service = Google::Apis::CalendarV3::CalendarService.new
  @service.authorization = authorize unless skip_auth
end

Instance Method Details

#authenticateObject



140
141
142
143
144
145
# File 'lib/utilities/gcal/service.rb', line 140

def authenticate
  perform_auth_flow
  {success: true}
rescue => e
  {success: false, error: e.message}
end

#list_calendarsObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/utilities/gcal/service.rb', line 65

def list_calendars
  results = @service.list_calendar_lists

  calendars = results.items.map do |calendar|
    {
      id: calendar.id,
      summary: calendar.summary,
      description: calendar.description,
      time_zone: calendar.time_zone,
      access_role: calendar.access_role,
      primary: calendar.primary
    }
  end

  {calendars: calendars, count: calendars.length}
rescue Google::Apis::Error => e
  raise "Google Calendar API Error: #{e.message}"
rescue => e
  log_error("list_calendars", e)
  raise e
end

#list_events(start_date: nil, end_date: nil, max_results: 20, calendar_id: "primary") ⇒ Object



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
# File 'lib/utilities/gcal/service.rb', line 27

def list_events(start_date: nil, end_date: nil, max_results: 20, calendar_id: "primary")
  # Default to today if no start date provided
  now = Time.now
  start_time = start_date ? Time.parse("#{start_date} 00:00:00") : Time.new(now.year, now.month, now.day, 0, 0, 0)
  # Default to 7 days from start if no end date provided
  end_time = end_date ? Time.parse("#{end_date} 23:59:59") : start_time + 7 * 24 * 60 * 60

  results = @service.list_events(
    calendar_id,
    max_results: max_results,
    single_events: true,
    order_by: "startTime",
    time_min: start_time.utc.iso8601,
    time_max: end_time.utc.iso8601
  )

  events = results.items.map do |event|
    {
      id: event.id,
      summary: event.summary,
      description: event.description,
      location: event.location,
      start: format_event_time(event.start),
      end: format_event_time(event.end),
      attendees: format_attendees(event.attendees),
      html_link: event.html_link,
      calendar_id: calendar_id
    }
  end

  {events: events, count: events.length}
rescue Google::Apis::Error => e
  raise "Google Calendar API Error: #{e.message}"
rescue => e
  log_error("list_events", e)
  raise e
end

#perform_auth_flowObject



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
# File 'lib/utilities/gcal/service.rb', line 147

def perform_auth_flow
  client_id = Mcpeasy::Config.google_client_id
  client_secret = Mcpeasy::Config.google_client_secret

  unless client_id && client_secret
    raise "Google credentials not found. Please save your credentials.json file using: mcpz config set_google_credentials <path_to_credentials.json>"
  end

  # Create credentials using OAuth2 flow with localhost redirect
  redirect_uri = "http://localhost:8080"
  client = Signet::OAuth2::Client.new(
    client_id: client_id,
    client_secret: client_secret,
    scope: SCOPE,
    redirect_uri: redirect_uri,
    authorization_uri: "https://accounts.google.com/o/oauth2/auth",
    token_credential_uri: "https://oauth2.googleapis.com/token"
  )

  # Generate authorization URL
  url = client.authorization_uri.to_s

  puts "DEBUG: Client ID: #{client_id[0..20]}..."
  puts "DEBUG: Scope: #{SCOPE}"
  puts "DEBUG: Redirect URI: #{redirect_uri}"
  puts

  # Start callback server to capture OAuth code
  puts "Starting temporary web server to capture OAuth callback..."
  puts "Opening authorization URL in your default browser..."
  puts url
  puts

  # Automatically open URL in default browser on macOS/Unix
  if system("which open > /dev/null 2>&1")
    system("open", url)
  else
    puts "Could not automatically open browser. Please copy the URL above manually."
  end
  puts
  puts "Waiting for OAuth callback... (will timeout in 60 seconds)"

  # Wait for the authorization code with timeout
  code = GoogleAuthServer.capture_auth_code

  unless code
    raise "Failed to receive authorization code. Please try again."
  end

  puts "✅ Authorization code received!"
  client.code = code
  client.fetch_access_token!

  # Save credentials to config
  credentials_data = {
    client_id: client.client_id,
    client_secret: client.client_secret,
    scope: client.scope,
    refresh_token: client.refresh_token,
    access_token: client.access_token,
    expires_at: client.expires_at
  }

  Mcpeasy::Config.save_google_token(credentials_data)
  puts "✅ Authentication successful! Token saved to config"

  client
rescue => e
  log_error("perform_auth_flow", e)
  raise "Authentication flow failed: #{e.message}"
end

#search_events(query, start_date: nil, end_date: nil, max_results: 10) ⇒ Object



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
# File 'lib/utilities/gcal/service.rb', line 87

def search_events(query, start_date: nil, end_date: nil, max_results: 10)
  # Default to today if no start date provided
  now = Time.now
  start_time = start_date ? Time.parse("#{start_date} 00:00:00") : Time.new(now.year, now.month, now.day, 0, 0, 0)
  # Default to 30 days from start if no end date provided
  end_time = end_date ? Time.parse("#{end_date} 23:59:59") : start_time + 30 * 24 * 60 * 60

  results = @service.list_events(
    "primary",
    q: query,
    max_results: max_results,
    single_events: true,
    order_by: "startTime",
    time_min: start_time.utc.iso8601,
    time_max: end_time.utc.iso8601
  )

  events = results.items.map do |event|
    {
      id: event.id,
      summary: event.summary,
      description: event.description,
      location: event.location,
      start: format_event_time(event.start),
      end: format_event_time(event.end),
      attendees: format_attendees(event.attendees),
      html_link: event.html_link,
      calendar_id: "primary"
    }
  end

  {events: events, count: events.length}
rescue Google::Apis::Error => e
  raise "Google Calendar API Error: #{e.message}"
rescue => e
  log_error("search_events", e)
  raise e
end

#test_connectionObject



126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/utilities/gcal/service.rb', line 126

def test_connection
  calendar = @service.get_calendar("primary")
  {
    ok: true,
    user: calendar.summary,
    email: calendar.id
  }
rescue Google::Apis::Error => e
  raise "Google Calendar API Error: #{e.message}"
rescue => e
  log_error("test_connection", e)
  raise e
end