Class: Gdrive::Service

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

Constant Summary collapse

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

MIME type mappings for Google Workspace documents

{
  "application/vnd.google-apps.document" => {
    format: "text/markdown",
    extension: ".md"
  },
  "application/vnd.google-apps.spreadsheet" => {
    format: "text/csv",
    extension: ".csv"
  },
  "application/vnd.google-apps.presentation" => {
    format: "text/plain",
    extension: ".txt"
  },
  "application/vnd.google-apps.drawing" => {
    format: "image/png",
    extension: ".png"
  }
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(skip_auth: false) ⇒ Service

Returns a new instance of Service.



41
42
43
44
45
# File 'lib/utilities/gdrive/service.rb', line 41

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

Instance Method Details

#authenticateObject



143
144
145
146
147
148
# File 'lib/utilities/gdrive/service.rb', line 143

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

#get_file_content(file_id) ⇒ Object



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

def get_file_content(file_id)
  # First get file metadata
  file = @service.get_file(file_id, fields: "id,name,mimeType,size")

  content = if EXPORT_FORMATS.key?(file.mime_type)
    # Export Google Workspace document
    export_format = EXPORT_FORMATS[file.mime_type][:format]
    @service.export_file(file_id, export_format)
  else
    # Download regular file
    @service.get_file(file_id, download_dest: StringIO.new)
  end

  {
    id: file.id,
    name: file.name,
    mime_type: file.mime_type,
    size: file.size&.to_i,
    content: content.is_a?(StringIO) ? content.string : content
  }
rescue Google::Apis::Error => e
  raise "Google Drive API Error: #{e.message}"
rescue => e
  log_error("get_file_content", e)
  raise e
end

#list_files(max_results: 20) ⇒ Object



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

def list_files(max_results: 20)
  results = @service.list_files(
    q: "trashed=false",
    page_size: max_results,
    order_by: "modifiedTime desc",
    fields: "files(id,name,mimeType,size,modifiedTime,webViewLink)"
  )

  files = results.files.map do |file|
    {
      id: file.id,
      name: file.name,
      mime_type: file.mime_type,
      size: file.size&.to_i,
      modified_time: file.modified_time,
      web_view_link: file.web_view_link
    }
  end

  {files: files, count: files.length}
rescue Google::Apis::Error => e
  raise "Google Drive API Error: #{e.message}"
rescue => e
  log_error("list_files", e)
  raise e
end

#perform_auth_flowObject



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

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_files(query, max_results: 10) ⇒ Object



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

def search_files(query, max_results: 10)
  results = @service.list_files(
    q: "fullText contains '#{query.gsub("'", "\\'")}' and trashed=false",
    page_size: max_results,
    fields: "files(id,name,mimeType,size,modifiedTime,webViewLink)"
  )

  files = results.files.map do |file|
    {
      id: file.id,
      name: file.name,
      mime_type: file.mime_type,
      size: file.size&.to_i,
      modified_time: file.modified_time,
      web_view_link: file.web_view_link
    }
  end

  {files: files, count: files.length}
rescue Google::Apis::Error => e
  raise "Google Drive API Error: #{e.message}"
rescue => e
  log_error("search_files", e)
  raise e
end

#test_connectionObject



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/utilities/gdrive/service.rb', line 127

def test_connection
  about = @service.get_about(fields: "user,storageQuota")
  {
    ok: true,
    user: about.user.display_name,
    email: about.user.email_address,
    storage_used: about.storage_quota&.usage,
    storage_limit: about.storage_quota&.limit
  }
rescue Google::Apis::Error => e
  raise "Google Drive API Error: #{e.message}"
rescue => e
  log_error("test_connection", e)
  raise e
end