Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.1 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)
from products.warehouse_sources.sources.todoist._config import TodoistSourceConfig
from products.warehouse_sources.sources.todoist.settings import ENDPOINTS, INCREMENTAL_FIELDS, TODOIST_ENDPOINTS
from products.warehouse_sources.sources.todoist.todoist import (
    TodoistResumeConfig,
    todoist_source,
    validate_credentials as validate_todoist_credentials,
)


@SourceRegistry.register
class TodoistSource(ResumableSource[TodoistSourceConfig, TodoistResumeConfig]):
    codebase_detection = detect(
        env=("^TODOIST_",), npm=("@doist/todoist-api-typescript",), pypi=("todoist-api-python", "todoist-python")
    )

    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://developer.todoist.com/api/v1"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.TODOIST

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.TODOIST,
            category=DataWarehouseSourceCategory.PRODUCTIVITY,
            label="Todoist",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Enter your Todoist API token to automatically pull your Todoist data into the PostHog Data warehouse.

You can find your personal API token in [Todoist's integration settings](https://app.todoist.com/app/settings/integrations/developer).""",
            iconPath="/static/services/todoist.png",
            docsUrl="https://posthog.com/docs/cdp/sources/todoist",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_token",
                        label="API token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="0123456789abcdef...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.todoist.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # A bad, revoked, or insufficiently-scoped token surfaces as a requests HTTPError when
            # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential
            # problem, so stop the sync. Match the stable status text and base host, not the
            # per-request path/query.
            "401 Client Error: Unauthorized for url: https://api.todoist.com": "Your Todoist API token is invalid or has been revoked. Generate a new token in your Todoist integration settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.todoist.com": "Your Todoist API token is missing the permissions needed to sync this data. Reconnect with a token that has the required access.",
        }

    def get_schemas(
        self,
        config: TodoistSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Todoist's v1 REST endpoints expose no server-side timestamp filter, so every endpoint is
        # full refresh (empty INCREMENTAL_FIELDS) — no genuine incremental/append mode to offer.
        return build_endpoint_schemas(
            ENDPOINTS,
            INCREMENTAL_FIELDS,
            names,
            should_sync_default={name: cfg.should_sync_default for name, cfg in TODOIST_ENDPOINTS.items()},
        )

    def validate_credentials(
        self,
        config: TodoistSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_todoist_credentials(config.api_token):
            return True, None

        return False, "Invalid Todoist API token"

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TodoistResumeConfig]:
        return ResumableSourceManager[TodoistResumeConfig](inputs, TodoistResumeConfig)

    def source_for_pipeline(
        self,
        config: TodoistSourceConfig,
        resumable_source_manager: ResumableSourceManager[TodoistResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return todoist_source(
            api_token=config.api_token,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
        )