Skip to content

Personal AI, On Personal Devices

Python

feat: add Google Drive connector with file export and sync

krypticmouse89e757adba4a
diff --git a/src/openjarvis/connectors/__init__.py b/src/openjarvis/connectors/__init__.py
index 1bc5dd24..4b5fae08 100644
--- a/src/openjarvis/connectors/__init__.py
+++ b/src/openjarvis/connectors/__init__.py
@@ -18,6 +18,11 @@ try:
except ImportError:
pass # httpx may not be installed
+try:
+ import openjarvis.connectors.gdrive # noqa: F401
+except ImportError:
+ pass # httpx may not be installed
+
try:
import openjarvis.connectors.notion # noqa: F401
except ImportError:
diff --git a/src/openjarvis/connectors/gdrive.py b/src/openjarvis/connectors/gdrive.py
new file mode 100644
index 00000000..ff73fbbe
--- /dev/null
+++ b/src/openjarvis/connectors/gdrive.py
@@ -0,0 +1,342 @@
+"""Google Drive connector — bulk file sync via the Drive REST API v3.
+
+Uses OAuth 2.0 tokens stored locally (see :mod:`openjarvis.connectors.oauth`).
+All network calls are isolated in module-level functions (``_gdrive_api_*``)
+to make them trivially mockable in tests.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any, Dict, Iterator, List, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.connectors.oauth import (
+ build_google_auth_url,
+ delete_tokens,
+ load_tokens,
+ save_tokens,
+)
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+from openjarvis.tools._stubs import ToolSpec
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_GDRIVE_API_BASE = "https://www.googleapis.com/drive/v3"
+_GDRIVE_SCOPE = "https://www.googleapis.com/auth/drive.readonly"
+_DEFAULT_CREDENTIALS_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "gdrive.json")
+
+# Map from Google Workspace MIME types to export MIME types
+_EXPORT_MIME_MAP: Dict[str, str] = {
+ "application/vnd.google-apps.document": "text/plain",
+ "application/vnd.google-apps.spreadsheet": "text/csv",
+ "application/vnd.google-apps.presentation": "text/plain",
+}
+
+# ---------------------------------------------------------------------------
+# Module-level API functions (easy to patch in tests)
+# ---------------------------------------------------------------------------
+
+
+def _gdrive_api_list_files(
+ token: str,
+ *,
+ page_token: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Call the Drive ``files.list`` endpoint.
+
+ Parameters
+ ----------
+ token:
+ OAuth access token.
+ page_token:
+ Pagination token from a previous response's ``nextPageToken``.
+
+ Returns
+ -------
+ dict
+ Raw API response containing ``files`` list and optional
+ ``nextPageToken``.
+ """
+ _fields = "nextPageToken,files(id,name,mimeType,modifiedTime,owners,webViewLink)"
+ params: Dict[str, Any] = {
+ "fields": _fields,
+ "pageSize": 100,
+ "orderBy": "modifiedTime desc",
+ }
+ if page_token:
+ params["pageToken"] = page_token
+
+ resp = httpx.get(
+ f"{_GDRIVE_API_BASE}/files",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params,
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def _gdrive_api_export(token: str, file_id: str, mime_type: str) -> str:
+ """Export a Google Workspace file as plain text or CSV.
+
+ Parameters
+ ----------
+ token:
+ OAuth access token.
+ file_id:
+ The Drive file ID to export.
+ mime_type:
+ The target MIME type for the export (e.g. ``"text/plain"``).
+
+ Returns
+ -------
+ str
+ Exported file content as a string.
+ """
+ resp = httpx.get(
+ f"{_GDRIVE_API_BASE}/files/{file_id}/export",
+ headers={"Authorization": f"Bearer {token}"},
+ params={"mimeType": mime_type},
+ timeout=60.0,
+ )
+ resp.raise_for_status()
+ return resp.text
+
+
+# ---------------------------------------------------------------------------
+# GDriveConnector
+# ---------------------------------------------------------------------------
+
+
+class GDriveConnector(BaseConnector):
+ """Connector that syncs files from Google Drive via the REST API v3.
+
+ Authentication is handled through Google OAuth 2.0. Tokens are stored
+ locally in a JSON credentials file.
+
+ Parameters
+ ----------
+ credentials_path:
+ Path to the JSON file where OAuth tokens are stored. Defaults to
+ ``~/.openjarvis/connectors/gdrive.json``.
+ """
+
+ connector_id = "gdrive"
+ display_name = "Google Drive"
+ auth_type = "oauth"
+
+ def __init__(self, credentials_path: str = "") -> None:
+ self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH
+ self._items_synced: int = 0
+ self._items_total: int = 0
+ self._last_sync: Optional[datetime] = None
+ self._last_cursor: Optional[str] = None
+
+ # ------------------------------------------------------------------
+ # BaseConnector interface
+ # ------------------------------------------------------------------
+
+ def is_connected(self) -> bool:
+ """Return ``True`` if a credentials file with a valid token exists."""
+ tokens = load_tokens(self._credentials_path)
+ if tokens is None:
+ return False
+ # Accept any non-empty dict that contains at least one key
+ # (simplified: real impl would also check expiry / refresh token)
+ return bool(tokens)
+
+ def disconnect(self) -> None:
+ """Delete the stored credentials file."""
+ delete_tokens(self._credentials_path)
+
+ def auth_url(self) -> str:
+ """Return a Google OAuth consent URL requesting ``drive.readonly`` scope."""
+ return build_google_auth_url(
+ client_id="", # placeholder — real client_id from config
+ scopes=[_GDRIVE_SCOPE],
+ )
+
+ def handle_callback(self, code: str) -> None:
+ """Handle the OAuth callback by persisting the authorization code.
+
+ In a full implementation this would exchange the code for tokens.
+ For now the code is saved directly as the token value.
+ """
+ save_tokens(self._credentials_path, {"token": code})
+
+ def sync(
+ self,
+ *,
+ since: Optional[datetime] = None, # noqa: ARG002 — reserved for future use
+ cursor: Optional[str] = None,
+ ) -> Iterator[Document]:
+ """Yield :class:`Document` objects for Google Drive files.
+
+ Paginates through the files.list API. Google Workspace files
+ (Docs, Sheets, Slides) are exported as plain text or CSV.
+ Non-exportable files are stored as metadata-only documents.
+
+ Parameters
+ ----------
+ since:
+ Not yet used (Drive API filtering is done server-side).
+ cursor:
+ ``nextPageToken`` from a previous sync to resume pagination.
+ """
+ tokens = load_tokens(self._credentials_path)
+ if not tokens:
+ return
+
+ token: str = tokens.get("token", tokens.get("access_token", ""))
+ if not token:
+ return
+
+ page_token: Optional[str] = cursor
+ synced = 0
+
+ while True:
+ list_resp = _gdrive_api_list_files(token, page_token=page_token)
+ files: List[Dict[str, Any]] = list_resp.get("files", [])
+
+ for file_meta in files:
+ file_id: str = file_meta.get("id", "")
+ if not file_id:
+ continue
+
+ name: str = file_meta.get("name", "")
+ mime_type: str = file_meta.get("mimeType", "")
+ web_view_link: Optional[str] = file_meta.get("webViewLink")
+
+ # Determine author from first owner
+ owners: List[Dict[str, str]] = file_meta.get("owners", [])
+ author: str = owners[0].get("displayName", "") if owners else ""
+
+ # Export Google Workspace types; store metadata for others
+ export_mime = _EXPORT_MIME_MAP.get(mime_type)
+ if export_mime is not None:
+ try:
+ content = _gdrive_api_export(token, file_id, export_mime)
+ except Exception: # noqa: BLE001
+ content = f"[File: {name}] ({mime_type})"
+ else:
+ content = f"[File: {name}] ({mime_type})"
+
+ doc = Document(
+ doc_id=f"gdrive:{file_id}",
+ source="gdrive",
+ doc_type="document",
+ content=content,
+ title=name,
+ author=author,
+ url=web_view_link,
+ metadata={
+ "file_id": file_id,
+ "mime_type": mime_type,
+ },
+ )
+ synced += 1
+ yield doc
+
+ next_page: Optional[str] = list_resp.get("nextPageToken")
+ if not next_page:
+ self._last_cursor = None
+ break
+ page_token = next_page
+ self._last_cursor = next_page
+
+ self._items_synced = synced
+ self._last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ """Return sync progress from the most recent :meth:`sync` call."""
+ return SyncStatus(
+ state="idle",
+ items_synced=self._items_synced,
+ last_sync=self._last_sync,
+ cursor=self._last_cursor,
+ )
+
+ # ------------------------------------------------------------------
+ # MCP tools
+ # ------------------------------------------------------------------
+
+ def mcp_tools(self) -> List[ToolSpec]:
+ """Expose three MCP tool specs for real-time Google Drive queries."""
+ return [
+ ToolSpec(
+ name="gdrive_search_files",
+ description=(
+ "Search Google Drive files using a query string. "
+ "Supports Drive search operators "
+ "(e.g. 'name contains \"report\" type:document')."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Drive search query",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum number of files to return",
+ "default": 20,
+ },
+ },
+ "required": ["query"],
+ },
+ category="productivity",
+ ),
+ ToolSpec(
+ name="gdrive_get_document",
+ description=(
+ "Retrieve the full text content of a Google Drive"
+ " document by file ID."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "file_id": {
+ "type": "string",
+ "description": "Google Drive file ID",
+ },
+ },
+ "required": ["file_id"],
+ },
+ category="productivity",
+ ),
+ ToolSpec(
+ name="gdrive_list_recent",
+ description=(
+ "List recently modified Google Drive files, "
+ "optionally filtered by file type."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "file_type": {
+ "type": "string",
+ "description": (
+ "Filter by Google Workspace type: "
+ "'document', 'spreadsheet', or 'presentation'"
+ ),
+ "default": "",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum number of files to return",
+ "default": 20,
+ },
+ },
+ "required": [],
+ },
+ category="productivity",
+ ),
+ ]
diff --git a/tests/connectors/test_gdrive.py b/tests/connectors/test_gdrive.py
new file mode 100644
index 00000000..1356fc41
--- /dev/null
+++ b/tests/connectors/test_gdrive.py
@@ -0,0 +1,177 @@
+"""Tests for GDriveConnector — OAuth-authenticated Google Drive sync connector.
+
+All Drive API calls are mocked; no network access is required.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import List
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+# ---------------------------------------------------------------------------
+# Helpers — fake API payloads
+# ---------------------------------------------------------------------------
+
+_FILES_LIST_RESPONSE = {
+ "files": [
+ {
+ "id": "doc1",
+ "name": "Q3 Roadmap",
+ "mimeType": "application/vnd.google-apps.document",
+ "modifiedTime": "2024-03-15T10:00:00.000Z",
+ "owners": [{"emailAddress": "[email protected]", "displayName": "Alice"}],
+ "webViewLink": "https://docs.google.com/document/d/doc1/edit",
+ },
+ {
+ "id": "sheet1",
+ "name": "Budget 2024",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ "modifiedTime": "2024-03-16T11:00:00.000Z",
+ "owners": [{"emailAddress": "[email protected]", "displayName": "Bob"}],
+ "webViewLink": "https://docs.google.com/spreadsheets/d/sheet1/edit",
+ },
+ ],
+ "nextPageToken": None,
+}
+
+_EXPORT_RESPONSE = "# Q3 Roadmap\n\nThis is the roadmap content."
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def connector(tmp_path: Path):
+ """GDriveConnector pointing at a tmp credentials path (no file yet)."""
+ from openjarvis.connectors.gdrive import GDriveConnector # noqa: PLC0415
+
+ creds_path = str(tmp_path / "gdrive.json")
+ return GDriveConnector(credentials_path=creds_path)
+
+
+# ---------------------------------------------------------------------------
+# Test 1 — not connected without a credentials file
+# ---------------------------------------------------------------------------
+
+
+def test_not_connected(connector) -> None:
+ """is_connected() returns False when no credentials file exists."""
+ assert connector.is_connected() is False
+
+
+# ---------------------------------------------------------------------------
+# Test 2 — auth_url contains drive.readonly scope
+# ---------------------------------------------------------------------------
+
+
+def test_auth_url(connector) -> None:
+ """auth_url() returns a Google OAuth URL with drive.readonly scope."""
+ url = connector.auth_url()
+ assert isinstance(url, str)
+ assert url.startswith("https://accounts.google.com/o/oauth2/v2/auth")
+ assert "drive.readonly" in url
+
+
+# ---------------------------------------------------------------------------
+# Test 3 — sync yields documents with correct fields (mocked API)
+# ---------------------------------------------------------------------------
+
+
+@patch("openjarvis.connectors.gdrive._gdrive_api_list_files")
+@patch("openjarvis.connectors.gdrive._gdrive_api_export")
+def test_sync_yields_documents(
+ mock_export,
+ mock_list,
+ connector,
+ tmp_path: Path,
+) -> None:
+ """sync() yields one Document per file with correct metadata."""
+ # Set up fake credentials so is_connected() returns True
+ creds_path = Path(connector._credentials_path)
+ creds_path.write_text(json.dumps({"token": "fake-access-token"}), encoding="utf-8")
+
+ # Configure mocks
+ mock_list.return_value = _FILES_LIST_RESPONSE
+ mock_export.return_value = _EXPORT_RESPONSE
+
+ docs: List[Document] = list(connector.sync())
+
+ assert len(docs) == 2
+
+ # --- Document 1 (Google Doc) ---
+ doc1 = next(d for d in docs if d.doc_id == "gdrive:doc1")
+ assert doc1.source == "gdrive"
+ assert doc1.doc_type == "document"
+ assert doc1.title == "Q3 Roadmap"
+ assert doc1.author == "Alice"
+ assert doc1.url == "https://docs.google.com/document/d/doc1/edit"
+ assert doc1.content == _EXPORT_RESPONSE
+
+ # --- Document 2 (Google Sheet) ---
+ doc2 = next(d for d in docs if d.doc_id == "gdrive:sheet1")
+ assert doc2.title == "Budget 2024"
+ assert doc2.author == "Bob"
+ assert doc2.url == "https://docs.google.com/spreadsheets/d/sheet1/edit"
+ assert doc2.content == _EXPORT_RESPONSE
+
+ # Verify the API was called correctly
+ mock_list.assert_called_once()
+ assert mock_export.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# Test 4 — disconnect removes the credentials file
+# ---------------------------------------------------------------------------
+
+
+def test_disconnect(connector, tmp_path: Path) -> None:
+ """disconnect() deletes the credentials file."""
+ creds_path = Path(connector._credentials_path)
+ creds_path.write_text(json.dumps({"token": "fake-access-token"}), encoding="utf-8")
+ assert connector.is_connected() is True
+
+ connector.disconnect()
+
+ assert not creds_path.exists()
+ assert connector.is_connected() is False
+
+
+# ---------------------------------------------------------------------------
+# Test 5 — mcp_tools returns the three expected tool specs
+# ---------------------------------------------------------------------------
+
+
+def test_mcp_tools(connector) -> None:
+ """mcp_tools() returns exactly 3 tools with the required names."""
+ tools = connector.mcp_tools()
+ names = {t.name for t in tools}
+ assert len(tools) == 3
+ assert "gdrive_search_files" in names
+ assert "gdrive_get_document" in names
+ assert "gdrive_list_recent" in names
+
+
+# ---------------------------------------------------------------------------
+# Test 6 — ConnectorRegistry contains "gdrive" after import
+# ---------------------------------------------------------------------------
+
+
+def test_registry() -> None:
+ """GDriveConnector can be registered and retrieved via ConnectorRegistry."""
+ from openjarvis.connectors.gdrive import GDriveConnector # noqa: PLC0415
+
+ # The registry is cleared before each test by the autouse conftest fixture,
+ # so we imperatively re-register here (same pattern as test_gmail.py).
+ ConnectorRegistry.register_value("gdrive", GDriveConnector)
+ assert ConnectorRegistry.contains("gdrive")
+ cls = ConnectorRegistry.get("gdrive")
+ assert cls.connector_id == "gdrive"