diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 482eb56..98933b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,8 @@ jobs: quality: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - run: python -m pip install -e ".[dev]" @@ -32,14 +32,14 @@ jobs: python: "3.12" runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} - run: python -m pip install -e ".[dev]" - name: Regressions, source archive and coverage run: python -m pytest tests -m "not integration" --cov=meta_ads_collector --cov-branch --cov-report=xml --junitxml=ci-results/unit.xml - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: tests-${{ matrix.os }}-${{ matrix.python }} @@ -49,8 +49,8 @@ jobs: distribution: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - run: python -m pip install -e ".[dev]" @@ -60,15 +60,38 @@ jobs: run: python scripts/check_distribution.py - name: Exact minimum dependency regression suite run: python scripts/check_distribution.py --minimum - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: release-distributions path: dist/ - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: distribution-tests path: ci-results/ + live-proxy: + needs: [distribution] + runs-on: macos-latest + timeout-minutes: 10 + env: + METAADS_CI_PROXY: ${{ secrets.METAADS_CI_PROXY }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - run: python -m pip install packaging + - uses: actions/download-artifact@v8 + with: + name: release-distributions + path: dist/ + - name: Actual Meta SOCKS modes with matched family sessions and safe metadata + run: python scripts/check_distribution.py --live --proxy-diagnostics + - uses: actions/upload-artifact@v7 + if: always() + with: + name: live-proxy-tests + path: ci-results/ live-connectivity: needs: [quality, test, distribution] runs-on: macos-latest @@ -76,18 +99,18 @@ jobs: env: METAADS_CI_PROXY: ${{ secrets.METAADS_CI_PROXY }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - run: python -m pip install packaging - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: release-distributions path: dist/ - name: Bounded actual Meta connectivity and field check run: python scripts/check_distribution.py --live --preflight - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: live-connectivity-tests @@ -103,14 +126,14 @@ jobs: os: windows-latest runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} - run: python -m pip install -e ".[dev,mcp]" - name: MCP contracts, storage, jobs, recovery and actual stdio protocol run: python -m pytest mcp/tests -m "not mcp_live" --cov=meta_ads_collector_mcp --cov-branch --junitxml=mcp/test-results/unit.xml - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: mcp-${{ matrix.os }}-${{ matrix.python }} @@ -119,17 +142,17 @@ jobs: needs: [distribution, mcp-tests] runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: release-distributions path: dist/ - name: Installed optional extra outside checkout run: python mcp/check_distribution.py - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: mcp-wheel-tests @@ -141,17 +164,17 @@ jobs: env: METAADS_CI_PROXY: ${{ secrets.METAADS_CI_PROXY }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: release-distributions path: dist/ - name: Actual Meta through installed MCP extra, including worker crash recovery run: python mcp/check_distribution.py --live - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: mcp-live-tests @@ -163,18 +186,18 @@ jobs: env: METAADS_CI_PROXY: ${{ secrets.METAADS_CI_PROXY }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - run: python -m pip install packaging - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: release-distributions path: dist/ - name: Full actual Meta integration suite run: python scripts/check_distribution.py --live - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: live-meta-tests diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 426c1c2..6c09323 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,8 +23,8 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - name: Install documentation tools diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6ef38a6..f33c12a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,7 +18,7 @@ jobs: contents: read id-token: write steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: release-distributions path: dist/ @@ -31,8 +31,8 @@ jobs: env: METAADS_CI_PROXY: ${{ secrets.METAADS_CI_PROXY }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 with: python-version: "3.12" - run: python -m pip install packaging @@ -47,7 +47,7 @@ jobs: run: | python mcp/check_distribution.py --dist-dir published-dist python mcp/check_distribution.py --dist-dir published-dist --live - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 if: always() with: name: published-package-tests diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b9c648..cbef2b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,46 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.7.0] - 2026-10-22 + +### Added +- `MetaAdsClient.get_ad_insights()` / `AsyncMetaAdsClient.get_ad_insights()`: the Ad Library "See ad details" + query (`AdLibraryV3AdDetailsQuery`). `get_ad_details()` and `enrich_ad()` now attach its payload under + `ad_details`, so enriched ads carry EU/UK/BR transparency (age, gender and location audience, total reach, + per-country age/gender reach breakdown), US political demographic and regional insights, payer/beneficiary + data, advertiser page info (verification, category, Instagram handle and followers, about text, cover photo), + page spend by disclaimer, verified-voice context and violation types. +- New normalized `Ad` fields: `page_categories`, `impressions_text`, `impressions_index`, `extra_texts`, + `extra_links`, `extra_images`, `extra_videos`, `ad_details`, `eu_transparency`, `uk_transparency`, + `br_transparency`, `eu_total_reach`, `targets_eu`, `payer_beneficiary_data`, `aaa_info`, `insights`, + `page_spend`, `violation_types`, `verified_voice_context`, `is_violating_eu_siep`. `targeting`, + `age_gender_distribution`, `region_distribution` and `beneficiary_payers` are filled from the details payload. +- New `AdCreative` fields: `original_image_url`, `resized_image_url`, `watermarked_image_url`, + `watermarked_video_hd_url`, `watermarked_video_sd_url`, `image_crops`. +- New `PageInfo` fields: `verification`, `category`, `alias`, `entity_type`, `is_deleted`, `is_restricted`, + `is_profile_page`, `about`, `cover_photo_url`, `ig_username`, `ig_followers`, `ig_verified`. +- CSV exports share one schema (`meta_ads_collector.exports.CSV_COLUMNS`) and add `creative_video_url`, + `cta_text`, `cta_type`, `display_format`, `page_like_count`, `page_categories`, `categories`, `bylines`, + `impressions_text`, `reach_lower`, `reach_upper`, `eu_total_reach`, `payer_beneficiary`, `targeted_countries`, + `collation_id` and `collation_count` columns before `collected_at` and `api_fields`. + +### Changed +- `page.likes` and `page.is_deleted` are populated from search rows; `funding_entity` and `disclaimer` + mapping is unchanged. +- Media downloads alternate between the creative's regional `*.fbcdn.net` edge and Meta's generic + `scontent.xx.fbcdn.net` / `video.xx.fbcdn.net` host across the existing retry budget, so one unreachable edge + (for example behind a proxy) no longer fails the download. Non-Meta URLs are unchanged. +- CI: the bounded live connectivity check allows three bootstrap attempts and GitHub Actions are pinned to + their current Node 24 majors. Actual Meta invocations retry transport failures on the private proxy leg + (curl timeouts, upstream `CONNECT` 590, rate limits) up to twice; data and behaviour assertions still fail + on the first attempt. The local test gateways retry one stalled upstream attempt per client request. + +## [1.6.0] - 2026-10-01 + +### Added +- Optional MCP extension (`pip install "meta-ads-collector[mcp]"`) with durable jobs, monitoring and the + `meta-ads-mcp` command; beginner quick starts in the README. + ## [1.5.1] - 2026-10-01 ### Fixed diff --git a/README.md b/README.md index ca7d2a3..70b145a 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ with MetaAdsCollector() as collector: print(ad.id, advertiser) ``` -The library also supports pagination, async collection, filters, exports, media downloads, and HTTP/HTTPS/SOCKS proxies. Fields supplied by Meta are preserved in `ad.api_fields`; individual ads may lack spend, impressions, media, or audience details. JSON/JSONL exports retain `api_fields`; CSV includes it as a JSON column. +The library also supports pagination, async collection, filters, exports, media downloads, and HTTP/HTTPS/SOCKS proxies. Fields supplied by Meta are preserved in `ad.api_fields`; individual ads may lack spend, impressions, media, or audience details. JSON/JSONL exports retain `api_fields`; CSV includes it as a JSON column. Pass `--enrich` (or call `collector.enrich_ad(ad)`) to add the Ad Library "See ad details" payload: EU/UK transparency audience and reach, US political demographics, payer/beneficiary data and advertiser page details. MetaAdsCollector uses internal Meta endpoints. Meta can change or restrict access, so network, proxy, verification, or rate-limit failures can occur. An empty query result does not establish that no matching ads exist. Keep result limits small when starting, and check errors before treating a collection as complete. diff --git a/docs/api-reference.md b/docs/api-reference.md index 3d3ab79..8aea53a 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -137,7 +137,7 @@ Download media files for a single ad. #### `enrich_ad(ad) -> Ad` -Fetch additional detail data from the ad detail endpoint and merge into the ad object. Returns the original ad unchanged on failure. +Fetch the current search row and the "See ad details" payload for the ad (see `MetaAdsClient.get_ad_details`) and merge every missing field into a copy of the ad. The details payload is kept under `ad.ad_details` and inside `ad.api_fields`; EU/UK transparency, demographic insights, payer/beneficiary data and advertiser page info are normalized into `targeting`, `age_gender_distribution`, `region_distribution`, `beneficiary_payers`, `page` and the `eu_*`/`payer_beneficiary_data` fields. Returns the original ad unchanged on failure. #### `stream(query, ...) -> Iterator[tuple[str, dict[str, Any]]]` @@ -239,9 +239,13 @@ Search for ads via the GraphQL API. Returns `(response_data, next_cursor)`. Search for pages using the typeahead endpoint. Returns a list of page dicts. -#### `get_ad_details(ad_archive_id, page_id) -> dict` +#### `get_ad_details(ad_archive_id, page_id=None, country="ALL") -> dict` -Fetch detailed ad data. Tries the detail page first, then a page-scoped search. +Fetch detailed ad data. With `page_id`, runs a page-scoped search to obtain the current search row, then `get_ad_insights()` and attaches its payload under the `ad_details` key. Without `page_id`, only the (currently JS-challenged) HTML detail page is attempted. Raises `NotImplementedError` when nothing is available. + +#### `get_ad_insights(ad_archive_id, page_id, country="ALL") -> dict` + +Run the Ad Library "See ad details" query (`AdLibraryV3AdDetailsQuery`) and return its `ad_details` object: `advertiser` (page info, about text, page spend by disclaimer), `insights` (US political age/gender and regional reach), `transparency_by_location` (`eu_transparency`, `uk_transparency`, `br_transparency` with age, gender and location audience, total reach and per-country age/gender breakdown), `aaa_info` (payer/beneficiary data), `verified_voice_context`, `violation_types` and `is_violating_eu_siep`. Pass the result as the `ad_details` key of a search row to `Ad.from_graphql_response()`. Raises `MetaAdsError` when Meta returns no details and `RateLimitError` on rate limits. #### `close() -> None` @@ -308,6 +312,20 @@ Normalized ad schema for the fields parsed by this package. Meta may omit fields | `page_is_deleted`, `contains_sensitive_content`, `contains_digital_created_media`, `is_aaa_eligible` | `bool \| None` | Meta eligibility and content flags | | `has_user_reported`, `report_count`, `hide_data_status`, `gated_type` | `Any` | Reporting and visibility fields as returned | | `branded_content`, `event`, `menu_items`, `is_reshared`, `root_reshared_post`, `fev_info` | `Any` | Additional response fields where present | +| `page_categories` | `list[str]` | Advertiser page categories from the search row | +| `impressions_text`, `impressions_index` | `str \| None`, `int \| None` | Meta's impression bucket label (for example `>1M`) and index | +| `extra_texts`, `extra_links`, `extra_images`, `extra_videos` | `Any` | Additional creative variants as returned | +| `ad_details` | `dict \| None` | Lossless "See ad details" payload (set by `enrich_ad()` / `get_ad_details()`) | +| `eu_transparency`, `uk_transparency`, `br_transparency` | `dict \| None` | Regional transparency blocks: audience, reach and per-country breakdown | +| `eu_total_reach` | `int \| None` | EU total reach from `eu_transparency` | +| `targets_eu` | `bool \| None` | Whether the ad targets the EU | +| `payer_beneficiary_data` | `list[dict]` | `{"payer", "beneficiary"}` pairs from `aaa_info` | +| `aaa_info` | `dict \| None` | Payer/beneficiary block including takedown and violation flags | +| `insights` | `dict \| None` | US political `age_gender_data` and `location_data` | +| `page_spend` | `dict \| None` | Advertiser lifetime and weekly spend by disclaimer | +| `violation_types` | `list` | Violation types reported by Meta | +| `verified_voice_context` | `Any` | Verified-voice and financial-services payer/beneficiary context | +| `is_violating_eu_siep` | `bool \| None` | EU SIEP violation flag | | `collation_id` | `str \| None` | Collation group ID | | `collation_count` | `int \| None` | Number of collated variants | | `api_fields` | `dict \| None` | Deep copy of the complete API row, including unrecognized and nested fields; included in exports by default | @@ -339,6 +357,9 @@ Normalized ad schema for the fields parsed by this package. Meta may omit fields | `thumbnail_url` | `str \| None` | Video thumbnail URL | | `cta_text` | `str \| None` | Call-to-action text | | `cta_type` | `str \| None` | CTA type identifier | +| `original_image_url`, `resized_image_url`, `watermarked_image_url` | `str \| None` | Image variants as returned | +| `watermarked_video_hd_url`, `watermarked_video_sd_url` | `str \| None` | Watermarked video variants | +| `image_crops` | `Any` | Crop metadata as returned | ### class PageInfo @@ -350,6 +371,11 @@ Normalized ad schema for the fields parsed by this package. Meta may omit fields | `page_url` | `str \| None` | `None` | Page URL | | `likes` | `int \| None` | `None` | Like count | | `verified` | `bool` | `False` | Verification status | +| `verification` | `str \| None` | `None` | `BLUE_VERIFIED`, `GRAY_VERIFIED` or `NOT_VERIFIED` (details query) | +| `category`, `alias`, `entity_type` | `str \| None` | `None` | Page category, vanity alias and entity type (details query) | +| `is_deleted`, `is_restricted`, `is_profile_page` | `bool \| None` | `None` | Page state flags | +| `about`, `cover_photo_url` | `str \| None` | `None` | About text and cover photo (details query) | +| `ig_username`, `ig_followers`, `ig_verified` | `str \| None`, `int \| None`, `bool \| None` | `None` | Linked Instagram account (details query) | ### class PageSearchResult diff --git a/mcp/check_distribution.py b/mcp/check_distribution.py index 4d2648c..92e7a20 100644 --- a/mcp/check_distribution.py +++ b/mcp/check_distribution.py @@ -13,6 +13,33 @@ import zipfile from pathlib import Path +# Keep in sync with scripts/check_distribution.py (asserted by tests/test_ci_configuration.py). +LIVE_TRANSPORT_ERRORS = ( + r"Timeout", + r"timed out", + r"CurlError", + r"CONNECT tunnel", + r"\b590\b", + r"RateLimitError", + r"rate limit", + r"AuthenticationError", + r"SessionExpiredError", + r"Connection error", + r"ConnectionError", + r"ConnectionReset", + r"RemoteDisconnected", + r"Could not resolve", +) +LIVE_RERUNS = 2 +LIVE_RERUN_DELAY_SECONDS = 15 + + +def live_rerun_arguments() -> list[str]: + arguments = ["--reruns", str(LIVE_RERUNS), "--reruns-delay", str(LIVE_RERUN_DELAY_SECONDS)] + for pattern in LIVE_TRANSPORT_ERRORS: + arguments += ["--only-rerun", pattern] + return arguments + def main(): parser = argparse.ArgumentParser(description=__doc__) @@ -68,7 +95,8 @@ def main(): ) assert missing_extra.returncode == 2 and "[mcp]" in missing_extra.stderr subprocess.run( - [str(python), "-m", "pip", "install", str(wheel) + "[mcp]", "pytest", "pytest-asyncio", "pytest-cov"], + [str(python), "-m", "pip", "install", str(wheel) + "[mcp]", "pytest", "pytest-asyncio", "pytest-cov", + "pytest-rerunfailures"], cwd=work, env=environment, check=True, @@ -112,7 +140,7 @@ def main(): "--junitxml=" + str(report), ] if args.live: - command.append("--run-mcp-live") + command += ["--run-mcp-live", *live_rerun_arguments()] subprocess.run(command, cwd=work, env=environment, check=True) diff --git a/meta_ads_collector/__init__.py b/meta_ads_collector/__init__.py index 7ffa2b6..22e6ebb 100644 --- a/meta_ads_collector/__init__.py +++ b/meta_ads_collector/__init__.py @@ -32,7 +32,7 @@ from .url_parser import extract_page_id_from_url from .webhooks import WebhookSender -__version__ = "1.6.0" +__version__ = "1.7.0" __all__ = [ # Models "Ad", diff --git a/meta_ads_collector/async_client.py b/meta_ads_collector/async_client.py index 8b3595f..fda7fba 100644 --- a/meta_ads_collector/async_client.py +++ b/meta_ads_collector/async_client.py @@ -14,8 +14,9 @@ from curl_cffi.requests import AsyncSession as CffiAsyncSession -from .client import MetaAdsClient +from .client import MetaAdsClient, parse_ad_details_response from .constants import ( + DOC_ID_AD_DETAILS, DOC_ID_SEARCH, DOC_ID_TYPEAHEAD, FALLBACK_REV, @@ -698,10 +699,54 @@ async def search_pages( logger.error("Typeahead search failed: %s", exc) return [] + async def get_ad_insights( + self, ad_archive_id: str, page_id: str, country: str = "ALL", + ) -> dict[str, Any]: + """Fetch the "See ad details" payload (async version). + + Same parameters, return value and errors as + :meth:`~meta_ads_collector.client.MetaAdsClient.get_ad_insights`. + """ + import uuid + + if not self._initialized: + await self.initialize() + + variables = { + "adArchiveID": str(ad_archive_id), + "pageID": str(page_id), + "country": country, + "sessionID": str(uuid.uuid4()), + "source": None, + "isAdNonPolitical": False, + "isAdNotAAAEligible": False, + } + doc_id = self._doc_ids.get("AdLibraryV3AdDetailsQuery", DOC_ID_AD_DETAILS) + payload = self._build_graphql_payload( + doc_id=doc_id, variables=variables, friendly_name="AdLibraryV3AdDetailsQuery", + ) + headers = dict(self._fingerprint.get_graphql_headers()) + headers["x-fb-friendly-name"] = "AdLibraryV3AdDetailsQuery" + headers["x-fb-lsd"] = self._tokens.get("lsd", "") + if "x-asbd-id" in self._tokens: + headers["x-asbd-id"] = self._tokens["x-asbd-id"] + headers["referer"] = f"{self.AD_LIBRARY_URL}?id={ad_archive_id}" + + response = await self._make_request( + "POST", self.GRAPHQL_URL, data=payload, headers=headers, + ) + if response.status_code != 200: + raise MetaAdsError(f"Ad details request failed with status {response.status_code}") + text = response.text + if text.startswith("for (;;);"): + text = text[9:] + return parse_ad_details_response(json.loads(text), ad_archive_id) + async def get_ad_details( self, ad_archive_id: str, page_id: str | None = None, + country: str = "ALL", ) -> dict[str, Any]: """Fetch detailed ad data (async version). @@ -714,7 +759,10 @@ async def get_ad_details( filtered by *page_id*, looking for the specific ``ad_archive_id`` in the results. - 2. **Ad Library detail page** (best-effort fallback): loads + 2. **Ad details query**: :meth:`get_ad_insights`, attached under + the ``ad_details`` key. + + 3. **Ad Library detail page** (best-effort fallback): loads ``/ads/library/?id={archive_id}`` and extracts embedded JSON from the server-rendered HTML. The page currently answers curl_cffi with a 403 JS challenge, so any non-200 response @@ -723,6 +771,9 @@ async def get_ad_details( if not self._initialized: await self.initialize() + row: dict[str, Any] | None = None + details: dict[str, Any] | None = None + # Approach 1: page-scoped GraphQL search if page_id: try: @@ -742,11 +793,26 @@ async def get_ad_details( or "" ) if found_id == str(ad_archive_id): - return dict(ad_data) + row = dict(ad_data) + break except Exception as exc: logger.debug("Approach 1 failed for ad %s: %s", ad_archive_id, exc) - # Approach 2: detail page (best-effort; may be 403-challenged) + # Approach 2: ad details query + try: + details = await self.get_ad_insights(ad_archive_id, page_id, country=country) + except Exception as exc: + logger.warning("Ad details query failed for ad %s: %s", ad_archive_id, exc) + + if row is not None or details is not None: + result: dict[str, Any] = row if row is not None else { + "ad_archive_id": str(ad_archive_id), "page_id": str(page_id), + } + if details is not None: + result["ad_details"] = details + return result + + # Approach 3: detail page (best-effort; may be 403-challenged) try: headers = dict(self._fingerprint.get_default_headers()) headers["referer"] = self.AD_LIBRARY_URL @@ -773,11 +839,11 @@ async def get_ad_details( return detail_data else: logger.debug( - "Approach 2: detail page returned HTTP %d for ad %s", + "Approach 3: detail page returned HTTP %d for ad %s", response.status_code, ad_archive_id, ) except Exception as exc: - logger.debug("Approach 2 failed for ad %s: %s", ad_archive_id, exc) + logger.debug("Approach 3 failed for ad %s: %s", ad_archive_id, exc) raise NotImplementedError( f"Could not retrieve detail data for ad {ad_archive_id}. " diff --git a/meta_ads_collector/async_collector.py b/meta_ads_collector/async_collector.py index 9781b3f..b231fa5 100644 --- a/meta_ads_collector/async_collector.py +++ b/meta_ads_collector/async_collector.py @@ -60,6 +60,7 @@ RateLimitError, SessionExpiredError, ) +from .exports import CSV_COLUMNS, ad_to_csv_row from .filters import FilterConfig, passes_filter from .models import Ad, PageSearchResult from .proxy_pool import ProxyPool @@ -602,19 +603,9 @@ async def collect_to_csv( path = Path(output_path) path.parent.mkdir(parents=True, exist_ok=True) - columns = [ - "id", "page_id", "page_name", "page_url", "is_active", - "ad_status", "delivery_start_time", "delivery_stop_time", - "creative_body", "creative_title", "creative_description", - "creative_link_url", "creative_image_url", "snapshot_url", - "impressions_lower", "impressions_upper", "spend_lower", - "spend_upper", "currency", "publisher_platforms", "languages", - "funding_entity", "disclaimer", "ad_type", "collected_at", "api_fields", - ] - count = 0 with open(path, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=columns) + writer = csv.DictWriter(f, fieldnames=list(CSV_COLUMNS)) writer.writeheader() async for ad in self.search( @@ -623,36 +614,7 @@ async def collect_to_csv( sort_by=sort_by, max_results=max_results, page_size=page_size, filter_config=filter_config, dedup_tracker=dedup_tracker, ): - primary = ad.creatives[0] if ad.creatives else None - row = { - "id": ad.id, - "page_id": ad.page.id if ad.page else "", - "page_name": ad.page.name if ad.page else "", - "page_url": ad.page.page_url if ad.page else "", - "is_active": ad.is_active if ad.is_active is not None else "", - "ad_status": ad.ad_status or "", - "delivery_start_time": ad.delivery_start_time.isoformat() if ad.delivery_start_time else "", - "delivery_stop_time": ad.delivery_stop_time.isoformat() if ad.delivery_stop_time else "", - "creative_body": primary.body if primary else "", - "creative_title": primary.title if primary else "", - "creative_description": primary.description if primary else "", - "creative_link_url": primary.link_url if primary else "", - "creative_image_url": primary.image_url if primary else "", - "snapshot_url": ad.snapshot_url or ad.ad_snapshot_url or "", - "impressions_lower": ad.impressions.lower_bound if ad.impressions else "", - "impressions_upper": ad.impressions.upper_bound if ad.impressions else "", - "spend_lower": ad.spend.lower_bound if ad.spend else "", - "spend_upper": ad.spend.upper_bound if ad.spend else "", - "currency": ad.currency or "", - "publisher_platforms": ",".join(ad.publisher_platforms), - "languages": ",".join(ad.languages), - "funding_entity": ad.funding_entity or "", - "disclaimer": ad.disclaimer or "", - "ad_type": ad.ad_type or "", - "collected_at": ad.collected_at.isoformat(), - "api_fields": json.dumps(ad.api_fields, ensure_ascii=False), - } - writer.writerow(row) + writer.writerow(ad_to_csv_row(ad)) count += 1 return count diff --git a/meta_ads_collector/cli.py b/meta_ads_collector/cli.py index 6039ef4..846ba23 100644 --- a/meta_ads_collector/cli.py +++ b/meta_ads_collector/cli.py @@ -16,6 +16,7 @@ from typing import Any, Optional from . import MetaAdsCollector +from .exports import CSV_COLUMNS, ad_to_csv_row from .logging_config import setup_logging as _setup_logging from .models import Ad @@ -451,49 +452,11 @@ def _write_ads_to_file( f.write("\n") count += 1 elif extension == ".csv": - columns = [ - "id", "page_id", "page_name", "page_url", "is_active", "ad_status", - "delivery_start_time", "delivery_stop_time", "creative_body", - "creative_title", "creative_description", "creative_link_url", - "creative_image_url", "snapshot_url", "impressions_lower", - "impressions_upper", "spend_lower", "spend_upper", "currency", - "publisher_platforms", "languages", "funding_entity", "disclaimer", - "ad_type", "collected_at", "api_fields", - ] with open(path, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=columns) + writer = csv.DictWriter(f, fieldnames=list(CSV_COLUMNS)) writer.writeheader() for ad in ads_iter: - primary = ad.creatives[0] if ad.creatives else None - row = { - "id": ad.id, - "page_id": ad.page.id if ad.page else "", - "page_name": ad.page.name if ad.page else "", - "page_url": ad.page.page_url if ad.page else "", - "is_active": ad.is_active if ad.is_active is not None else "", - "ad_status": ad.ad_status or "", - "delivery_start_time": ad.delivery_start_time.isoformat() if ad.delivery_start_time else "", - "delivery_stop_time": ad.delivery_stop_time.isoformat() if ad.delivery_stop_time else "", - "creative_body": primary.body if primary else "", - "creative_title": primary.title if primary else "", - "creative_description": primary.description if primary else "", - "creative_link_url": primary.link_url if primary else "", - "creative_image_url": primary.image_url if primary else "", - "snapshot_url": ad.snapshot_url or ad.ad_snapshot_url or "", - "impressions_lower": ad.impressions.lower_bound if ad.impressions else "", - "impressions_upper": ad.impressions.upper_bound if ad.impressions else "", - "spend_lower": ad.spend.lower_bound if ad.spend else "", - "spend_upper": ad.spend.upper_bound if ad.spend else "", - "currency": ad.currency or "", - "publisher_platforms": ",".join(ad.publisher_platforms), - "languages": ",".join(ad.languages), - "funding_entity": ad.funding_entity or "", - "disclaimer": ad.disclaimer or "", - "ad_type": ad.ad_type or "", - "collected_at": ad.collected_at.isoformat(), - "api_fields": _json.dumps(ad.api_fields, ensure_ascii=False), - } - writer.writerow(row) + writer.writerow(ad_to_csv_row(ad)) count += 1 else: # .json diff --git a/meta_ads_collector/client.py b/meta_ads_collector/client.py index de3da33..39795d3 100644 --- a/meta_ads_collector/client.py +++ b/meta_ads_collector/client.py @@ -23,6 +23,7 @@ DEFAULT_MAX_RETRIES, DEFAULT_RETRY_DELAY, DEFAULT_TIMEOUT, + DOC_ID_AD_DETAILS, DOC_ID_SEARCH, DOC_ID_TYPEAHEAD, FALLBACK_REV, @@ -32,6 +33,7 @@ from .exceptions import ( AuthenticationError, MetaAdsError, + RateLimitError, SessionExpiredError, ) from .fingerprint import BrowserFingerprint, generate_fingerprint @@ -40,6 +42,35 @@ logger = logging.getLogger(__name__) +def parse_ad_details_response(data: Any, ad_archive_id: str) -> dict[str, Any]: + """Extract the ``ad_details`` object from an ``AdLibraryV3AdDetailsQuery`` reply. + + Raises :class:`RateLimitError` when Meta reports a rate limit and + :class:`MetaAdsError` when the reply carries no details object. Partial + replies (``errors`` alongside a populated ``ad_details``) are returned + as-is because Meta uses field-level errors for sections it cannot fill. + """ + errors = data.get("errors") if isinstance(data, dict) else None + messages: list[str] = [] + for error in errors or []: + if not isinstance(error, dict): + continue + message = str(error.get("message", "Unknown error")) + if error.get("code") == 1675004 or "rate limit" in message.lower(): + raise RateLimitError(f"Ad details rate limited for ad {ad_archive_id}: {message}") + messages.append(message) + payload = data.get("data") if isinstance(data, dict) else None + main = payload.get("ad_library_main") if isinstance(payload, dict) else None + details = main.get("ad_details") if isinstance(main, dict) else None + if not isinstance(details, dict) or not details: + reason = "; ".join(messages) if messages else "empty ad_details payload" + raise MetaAdsError(f"Ad details unavailable for ad {ad_archive_id}: {reason}") + if messages: + logger.debug("Ad details for %s returned partial data: %s", ad_archive_id, messages) + return details + + + class MetaAdsClient: """ HTTP client for Meta Ad Library. @@ -1356,18 +1387,93 @@ def _parse_typeahead_response(self, data: dict[str, Any]) -> list[dict[str, Any] logger.error("Failed to parse typeahead response: %s", exc) return [] - def get_ad_details(self, ad_archive_id: str, page_id: Optional[str] = None) -> dict[str, Any]: + def get_ad_insights( + self, ad_archive_id: str, page_id: str, country: str = "ALL", + ) -> dict[str, Any]: + """Fetch the "See ad details" payload for one ad. + + Runs the ``AdLibraryV3AdDetailsQuery`` GraphQL document that the + Ad Library UI issues when an ad's details panel is opened. The + returned ``ad_details`` object holds everything that the search + row does not: advertiser page info (verification, category, + Instagram handle, likes, about text), page spend by disclaimer, + EU/UK/BR transparency (age, gender and location audience, total + reach and the per-country age/gender reach breakdown), US + political demographic and regional insights, payer/beneficiary + data, verified-voice context and violation types. + + Args: + ad_archive_id: The numeric archive ID of the ad. + page_id: The advertiser page ID (required by Meta). + country: Country code used by the UI; ``"ALL"`` returns the + complete payload. + + Returns: + The raw ``ad_details`` dict. Pass it as the ``ad_details`` + key of a search row to :meth:`Ad.from_graphql_response`. + + Raises: + MetaAdsError: If Meta returns no ``ad_details`` object. + RateLimitError: If Meta reports a rate limit. + """ + if not self._initialized: + self.initialize() + if self._is_session_stale(): + logger.info("Session is stale, refreshing before request...") + if not self._refresh_session(): + raise SessionExpiredError("Failed to refresh stale session") + + variables = { + "adArchiveID": str(ad_archive_id), + "pageID": str(page_id), + "country": country, + "sessionID": self._generate_session_id(), + "source": None, + # Both flags request the full payload; Meta returns null + # sections for ads where they do not apply. + "isAdNonPolitical": False, + "isAdNotAAAEligible": False, + } + doc_id = self._doc_ids.get("AdLibraryV3AdDetailsQuery", DOC_ID_AD_DETAILS) + payload = self._build_graphql_payload( + doc_id=doc_id, variables=variables, friendly_name="AdLibraryV3AdDetailsQuery", + ) + headers = dict(self._fingerprint.get_graphql_headers()) + headers["x-fb-friendly-name"] = "AdLibraryV3AdDetailsQuery" + headers["x-fb-lsd"] = self._tokens.get("lsd", "") + if "x-asbd-id" in self._tokens: + headers["x-asbd-id"] = self._tokens["x-asbd-id"] + headers["referer"] = f"{self.AD_LIBRARY_URL}?id={ad_archive_id}" + + response = self._make_graphql_request(payload, headers) + if response.status_code != 200: + raise MetaAdsError(f"Ad details request failed with status {response.status_code}") + text = response.text + if text.startswith("for (;;);"): + text = text[9:] + data = json.loads(text) + details = parse_ad_details_response(data, ad_archive_id) + self._consecutive_errors = 0 + return details + + def get_ad_details( + self, ad_archive_id: str, page_id: Optional[str] = None, country: str = "ALL", + ) -> dict[str, Any]: """Fetch detailed ad data beyond what search results provide. Approaches attempted (in order): 1. **Collated search with page_id**: If *page_id* is supplied, performs a targeted search filtered by page ID and looks for - the specific ``ad_archive_id`` in the results. This can - surface extra fields that are only returned when a page-scoped - query is made. + the specific ``ad_archive_id`` in the results. This yields + the current search row (creatives, page fields, metrics). - 2. **Ad Library detail page** (best-effort fallback): Loads + 2. **Ad details query**: If *page_id* is supplied, fetches the + "See ad details" payload with :meth:`get_ad_insights` and + attaches it under the ``ad_details`` key (EU/UK transparency, + demographic insights, payer/beneficiary data, advertiser info). + + 3. **Ad Library detail page** (best-effort fallback): Loads ``https://www.facebook.com/ads/library/?id={archive_id}`` and extracts embedded JSON data from the server-rendered HTML. NOTE: this page currently returns HTTP 403 (JS challenge) to @@ -1376,11 +1482,13 @@ def get_ad_details(self, ad_archive_id: str, page_id: Optional[str] = None) -> d Args: ad_archive_id: The numeric archive ID of the ad. - page_id: Optional page ID to enable approach 1. + page_id: Optional page ID to enable approaches 1 and 2. + country: Country code for the details query (default ``"ALL"``). Returns: A dict of parsed ad detail data. Keys are a superset of the - fields available in search results. + fields available in search results, plus ``ad_details`` when + the details query succeeded. Raises: NotImplementedError: If no approach yields useful data. @@ -1388,6 +1496,9 @@ def get_ad_details(self, ad_archive_id: str, page_id: Optional[str] = None) -> d if not self._initialized: self.initialize() + row: Optional[dict[str, Any]] = None + details: Optional[dict[str, Any]] = None + # ── Approach 1: targeted page-scoped search ─────────────── if page_id: try: @@ -1411,11 +1522,26 @@ def get_ad_details(self, ad_archive_id: str, page_id: Optional[str] = None) -> d "Approach 1 succeeded for ad %s via page %s", ad_archive_id, page_id, ) - return dict(ad_data) + row = dict(ad_data) + break except Exception as exc: logger.debug("Approach 1 failed for ad %s: %s", ad_archive_id, exc) - # ── Approach 2: Ad Library detail page (best effort) ────── + # ── Approach 2: ad details query ────────────────────── + try: + details = self.get_ad_insights(ad_archive_id, page_id, country=country) + except Exception as exc: + logger.warning("Ad details query failed for ad %s: %s", ad_archive_id, exc) + + if row is not None or details is not None: + result: dict[str, Any] = row if row is not None else { + "ad_archive_id": str(ad_archive_id), "page_id": str(page_id), + } + if details is not None: + result["ad_details"] = details + return result + + # ── Approach 3: Ad Library detail page (best effort) ────── # This page 403s non-browser clients at the moment, so tolerate # failure quickly and move on. try: @@ -1440,21 +1566,21 @@ def get_ad_details(self, ad_archive_id: str, page_id: Optional[str] = None) -> d detail_data = self._parse_ad_detail_page(response.text, ad_archive_id) if detail_data: logger.debug( - "Approach 2 succeeded for ad %s: %d fields", + "Approach 3 succeeded for ad %s: %d fields", ad_archive_id, len(detail_data), ) return detail_data logger.debug( - "Approach 2: page loaded but no detail data found for ad %s", + "Approach 3: page loaded but no detail data found for ad %s", ad_archive_id, ) else: logger.debug( - "Approach 2 failed for ad %s: HTTP %d", + "Approach 3 failed for ad %s: HTTP %d", ad_archive_id, response.status_code, ) except Exception as exc: - logger.debug("Approach 2 failed for ad %s: %s", ad_archive_id, exc) + logger.debug("Approach 3 failed for ad %s: %s", ad_archive_id, exc) raise NotImplementedError( f"Could not retrieve detail data for ad {ad_archive_id}. " diff --git a/meta_ads_collector/collector.py b/meta_ads_collector/collector.py index b29b0eb..7962c26 100644 --- a/meta_ads_collector/collector.py +++ b/meta_ads_collector/collector.py @@ -58,6 +58,7 @@ RateLimitError, SessionExpiredError, ) +from .exports import CSV_COLUMNS, ad_to_csv_row from .filters import FilterConfig, passes_filter from .media import MediaDownloader, MediaDownloadResult from .models import Ad, PageSearchResult @@ -1104,39 +1105,9 @@ def collect_to_csv( path = Path(output_path) path.parent.mkdir(parents=True, exist_ok=True) - # Define CSV columns (flattened schema) - columns = [ - "id", - "page_id", - "page_name", - "page_url", - "is_active", - "ad_status", - "delivery_start_time", - "delivery_stop_time", - "creative_body", - "creative_title", - "creative_description", - "creative_link_url", - "creative_image_url", - "snapshot_url", - "impressions_lower", - "impressions_upper", - "spend_lower", - "spend_upper", - "currency", - "publisher_platforms", - "languages", - "funding_entity", - "disclaimer", - "ad_type", - "collected_at", - "api_fields", - ] - count = 0 with open(path, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=columns) + writer = csv.DictWriter(f, fieldnames=list(CSV_COLUMNS)) writer.writeheader() for ad in self.search( @@ -1152,39 +1123,7 @@ def collect_to_csv( filter_config=filter_config, dedup_tracker=dedup_tracker, ): - # Flatten ad data for CSV - primary_creative = ad.creatives[0] if ad.creatives else None - - row = { - "id": ad.id, - "page_id": ad.page.id if ad.page else "", - "page_name": ad.page.name if ad.page else "", - "page_url": ad.page.page_url if ad.page else "", - "is_active": ad.is_active if ad.is_active is not None else "", - "ad_status": ad.ad_status or "", - "delivery_start_time": ad.delivery_start_time.isoformat() if ad.delivery_start_time else "", - "delivery_stop_time": ad.delivery_stop_time.isoformat() if ad.delivery_stop_time else "", - "creative_body": primary_creative.body if primary_creative else "", - "creative_title": primary_creative.title if primary_creative else "", - "creative_description": primary_creative.description if primary_creative else "", - "creative_link_url": primary_creative.link_url if primary_creative else "", - "creative_image_url": primary_creative.image_url if primary_creative else "", - "snapshot_url": ad.snapshot_url or ad.ad_snapshot_url or "", - "impressions_lower": ad.impressions.lower_bound if ad.impressions else "", - "impressions_upper": ad.impressions.upper_bound if ad.impressions else "", - "spend_lower": ad.spend.lower_bound if ad.spend else "", - "spend_upper": ad.spend.upper_bound if ad.spend else "", - "currency": ad.currency or "", - "publisher_platforms": ",".join(ad.publisher_platforms), - "languages": ",".join(ad.languages), - "funding_entity": ad.funding_entity or "", - "disclaimer": ad.disclaimer or "", - "ad_type": ad.ad_type or "", - "collected_at": ad.collected_at.isoformat(), - "api_fields": json.dumps(ad.api_fields, ensure_ascii=False), - } - - writer.writerow(row) + writer.writerow(ad_to_csv_row(ad)) count += 1 logger.info(f"Saved {count} ads to {output_path}") diff --git a/meta_ads_collector/constants.py b/meta_ads_collector/constants.py index 58efed1..a95002e 100644 --- a/meta_ads_collector/constants.py +++ b/meta_ads_collector/constants.py @@ -54,6 +54,10 @@ # --------------------------------------------------------------------------- DOC_ID_SEARCH = "25464068859919530" # AdLibrarySearchPaginationQuery DOC_ID_TYPEAHEAD = "9755915494515334" # useAdLibraryTypeaheadSuggestionDataSourceQuery +# AdLibraryV3AdDetailsQuery -- the "See ad details" panel: EU/UK/BR transparency, +# demographic insights, payer/beneficiary data and advertiser page info. +# Last verified working: 2026-10-22 +DOC_ID_AD_DETAILS = "25068828942793558" # --------------------------------------------------------------------------- # Fallback token values diff --git a/meta_ads_collector/exports.py b/meta_ads_collector/exports.py new file mode 100644 index 0000000..5ec06ab --- /dev/null +++ b/meta_ads_collector/exports.py @@ -0,0 +1,123 @@ +"""Shared flat CSV schema used by the CLI and both collectors. + +JSON and JSONL exports carry every :class:`~meta_ads_collector.models.Ad` +field. CSV cannot nest, so it exposes the most useful scalar fields as +columns and keeps the lossless Meta payload in the ``api_fields`` column. +""" + +from __future__ import annotations + +import json +from typing import Any + +from .models import Ad + +CSV_COLUMNS: tuple[str, ...] = ( + "id", + "page_id", + "page_name", + "page_url", + "is_active", + "ad_status", + "delivery_start_time", + "delivery_stop_time", + "creative_body", + "creative_title", + "creative_description", + "creative_link_url", + "creative_image_url", + "snapshot_url", + "impressions_lower", + "impressions_upper", + "spend_lower", + "spend_upper", + "currency", + "publisher_platforms", + "languages", + "funding_entity", + "disclaimer", + "ad_type", + # Columns added in 1.7.0 + "creative_video_url", + "cta_text", + "cta_type", + "display_format", + "page_like_count", + "page_categories", + "categories", + "bylines", + "impressions_text", + "reach_lower", + "reach_upper", + "eu_total_reach", + "payer_beneficiary", + "targeted_countries", + "collation_id", + "collation_count", + "collected_at", + "api_fields", +) + + +def _blank(value: Any) -> Any: + return "" if value is None else value + + +def _joined(values: Any) -> str: + if not isinstance(values, (list, tuple)): + return "" if values is None else str(values) + return ",".join(str(item) for item in values if item is not None) + + +def ad_to_csv_row(ad: Ad) -> dict[str, Any]: + """Flatten one ad into a row keyed by :data:`CSV_COLUMNS`.""" + primary = ad.creatives[0] if ad.creatives else None + page = ad.page + return { + "id": ad.id, + "page_id": page.id if page else "", + "page_name": page.name if page else "", + "page_url": _blank(page.page_url) if page else "", + "is_active": _blank(ad.is_active), + "ad_status": ad.ad_status or "", + "delivery_start_time": ad.delivery_start_time.isoformat() if ad.delivery_start_time else "", + "delivery_stop_time": ad.delivery_stop_time.isoformat() if ad.delivery_stop_time else "", + "creative_body": _blank(primary.body) if primary else "", + "creative_title": _blank(primary.title) if primary else "", + "creative_description": _blank(primary.description) if primary else "", + "creative_link_url": _blank(primary.link_url) if primary else "", + "creative_image_url": _blank(primary.image_url) if primary else "", + "snapshot_url": ad.snapshot_url or ad.ad_snapshot_url or "", + "impressions_lower": _blank(ad.impressions.lower_bound) if ad.impressions else "", + "impressions_upper": _blank(ad.impressions.upper_bound) if ad.impressions else "", + "spend_lower": _blank(ad.spend.lower_bound) if ad.spend else "", + "spend_upper": _blank(ad.spend.upper_bound) if ad.spend else "", + "currency": ad.currency or "", + "publisher_platforms": _joined(ad.publisher_platforms), + "languages": _joined(ad.languages), + "funding_entity": ad.funding_entity or "", + "disclaimer": ad.disclaimer or "", + "ad_type": ad.ad_type or "", + "creative_video_url": _blank(primary.video_url) if primary else "", + "cta_text": _blank(primary.cta_text) if primary else "", + "cta_type": _blank(primary.cta_type) if primary else "", + "display_format": ad.display_format or "", + "page_like_count": _blank(page.likes) if page else "", + "page_categories": _joined(ad.page_categories), + "categories": _joined(ad.categories), + "bylines": _joined(ad.bylines), + "impressions_text": ad.impressions_text or "", + "reach_lower": _blank(ad.reach.lower_bound) if ad.reach else "", + "reach_upper": _blank(ad.reach.upper_bound) if ad.reach else "", + "eu_total_reach": _blank(ad.eu_total_reach), + "payer_beneficiary": ";".join( + f"{_blank(item.get('payer'))}|{_blank(item.get('beneficiary'))}" + for item in ad.payer_beneficiary_data + if isinstance(item, dict) + ), + "targeted_countries": _joined(ad.targeted_or_reached_countries), + "collation_id": ad.collation_id or "", + "collation_count": _blank(ad.collation_count), + "collected_at": ad.collected_at.isoformat(), + "api_fields": json.dumps(ad.api_fields, ensure_ascii=False), + } diff --git a/meta_ads_collector/media.py b/meta_ads_collector/media.py index b476fb8..bc641a2 100644 --- a/meta_ads_collector/media.py +++ b/meta_ads_collector/media.py @@ -19,7 +19,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any -from urllib.parse import urlparse +from urllib.parse import urlparse, urlsplit, urlunsplit from curl_cffi.requests import Session as CffiSession from curl_cffi.requests.exceptions import ConnectionError as CffiConnectionError @@ -67,6 +67,31 @@ _CHUNK_SIZE: int = 65_536 +_FBCDN_SUFFIX = ".fbcdn.net" + + +def fallback_media_url(url: str) -> str | None: + """Return the same signed media path on Meta's generic CDN host, or ``None``. + + Meta serves a signed ``*.fbcdn.net`` path from any of its edges, and a + proxy exit can fail to reach one regional edge (``scontent.fxxx-1.fna``, + ``scontent-dus1-1.xx``) while the generic ``scontent.xx.fbcdn.net`` or + ``video.xx.fbcdn.net`` host still answers. Non-Meta hosts and URLs that + already use the generic host return ``None``. + """ + try: + parts = urlsplit(url) + except ValueError: + return None + host = (parts.hostname or "").lower() + if not host.endswith(_FBCDN_SUFFIX) or parts.port or parts.username: + return None + generic = "video.xx.fbcdn.net" if host.startswith("video") else "scontent.xx.fbcdn.net" + if host == generic: + return None + return urlunsplit(parts._replace(netloc=generic)) + + def detect_extension_from_url(url: str) -> str | None: """Detect a file extension from the URL path. @@ -258,19 +283,25 @@ def _download_file( logger.debug("Could not stat existing file %s: %s", local_path, exc) last_error: str | None = None + # Odd-numbered attempts use Meta's generic CDN host so one unreachable + # regional edge does not exhaust the whole retry budget. + fallback = fallback_media_url(url) for attempt in range(self.max_retries): partial_path: Path | None = None + attempt_url = fallback if fallback and attempt % 2 == 1 else url + if attempt_url is not url: + logger.debug("Retrying %s on the generic Meta CDN host", url) try: response = self.session.get( - url, stream=True, timeout=self.timeout, allow_redirects=True, + attempt_url, stream=True, timeout=self.timeout, allow_redirects=True, ) response.raise_for_status() # Resolve extension *after* the first response so we can # use Content-Type. If the extension changed, update the # local_path accordingly. - ext = self._resolve_extension(url, response) + ext = self._resolve_extension(attempt_url, response) if local_path.suffix != ext: local_path = local_path.with_suffix(ext) @@ -308,24 +339,24 @@ def _download_file( status = getattr(status, "status_code", None) if status else None last_error = f"HTTP {status}: {exc}" if status == 403: - logger.warning("URL likely expired (403 Forbidden): %s", url) + logger.warning("URL likely expired (403 Forbidden): %s", attempt_url) # No point retrying an expired token return False, last_error, None logger.warning( "HTTP error on attempt %d/%d for %s: %s", - attempt + 1, self.max_retries, url, exc, + attempt + 1, self.max_retries, attempt_url, exc, ) except CffiConnectionError as exc: last_error = f"Connection error: {exc}" logger.warning( "Connection error on attempt %d/%d for %s: %s", - attempt + 1, self.max_retries, url, exc, + attempt + 1, self.max_retries, attempt_url, exc, ) except CffiTimeout as exc: last_error = f"Timeout: {exc}" logger.warning( "Timeout on attempt %d/%d for %s: %s", - attempt + 1, self.max_retries, url, exc, + attempt + 1, self.max_retries, attempt_url, exc, ) except OSError as exc: last_error = f"IO error: {exc}" @@ -336,7 +367,7 @@ def _download_file( last_error = f"Unexpected error: {exc}" logger.warning( "Unexpected error on attempt %d/%d for %s: %s", - attempt + 1, self.max_retries, url, exc, + attempt + 1, self.max_retries, attempt_url, exc, ) finally: if partial_path is not None: diff --git a/meta_ads_collector/models.py b/meta_ads_collector/models.py index c7b65d6..39efbf4 100644 --- a/meta_ads_collector/models.py +++ b/meta_ads_collector/models.py @@ -162,6 +162,13 @@ class AdCreative: thumbnail_url: str | None = None cta_text: str | None = None cta_type: str | None = None + # Additional media variants Meta returns alongside the primary URLs + original_image_url: str | None = None + resized_image_url: str | None = None + watermarked_image_url: str | None = None + watermarked_video_hd_url: str | None = None + watermarked_video_sd_url: str | None = None + image_crops: Any = None def to_dict(self) -> dict[str, Any]: return {k: v for k, v in asdict(self).items() if v is not None} @@ -176,6 +183,19 @@ class PageInfo: page_url: str | None = None likes: int | None = None verified: bool = False + # Fields supplied by the ad details query (advertiser block) + verification: str | None = None # BLUE_VERIFIED, GRAY_VERIFIED, NOT_VERIFIED + category: str | None = None + alias: str | None = None + entity_type: str | None = None + is_deleted: bool | None = None + is_restricted: bool | None = None + is_profile_page: bool | None = None + about: str | None = None + cover_photo_url: str | None = None + ig_username: str | None = None + ig_followers: int | None = None + ig_verified: bool | None = None def to_dict(self) -> dict[str, Any]: return asdict(self) @@ -305,6 +325,28 @@ class Ad: is_reshared: bool | None = None root_reshared_post: Any = None fev_info: Any = None + page_categories: list[str] = field(default_factory=list) + impressions_text: str | None = None + impressions_index: int | None = None + extra_texts: Any = None + extra_links: Any = None + extra_images: Any = None + extra_videos: Any = None + + # Fields supplied by the ad details query (``ad_details`` payload) + ad_details: dict[str, Any] | None = None # lossless copy of the details payload + eu_transparency: dict[str, Any] | None = None + uk_transparency: dict[str, Any] | None = None + br_transparency: dict[str, Any] | None = None + eu_total_reach: int | None = None + targets_eu: bool | None = None + payer_beneficiary_data: list[dict[str, Any]] = field(default_factory=list) + aaa_info: dict[str, Any] | None = None + insights: dict[str, Any] | None = None + page_spend: dict[str, Any] | None = None + violation_types: list[Any] = field(default_factory=list) + verified_voice_context: Any = None + is_violating_eu_siep: bool | None = None # Metadata collation_id: str | None = None @@ -391,6 +433,26 @@ def to_dict(self, include_raw: bool = False) -> dict[str, Any]: "is_reshared": self.is_reshared, "root_reshared_post": self.root_reshared_post, "fev_info": self.fev_info, + "page_categories": self.page_categories, + "impressions_text": self.impressions_text, + "impressions_index": self.impressions_index, + "extra_texts": self.extra_texts, + "extra_links": self.extra_links, + "extra_images": self.extra_images, + "extra_videos": self.extra_videos, + "ad_details": deepcopy(self.ad_details), + "eu_transparency": deepcopy(self.eu_transparency), + "uk_transparency": deepcopy(self.uk_transparency), + "br_transparency": deepcopy(self.br_transparency), + "eu_total_reach": self.eu_total_reach, + "targets_eu": self.targets_eu, + "payer_beneficiary_data": deepcopy(self.payer_beneficiary_data), + "aaa_info": deepcopy(self.aaa_info), + "insights": deepcopy(self.insights), + "page_spend": deepcopy(self.page_spend), + "violation_types": deepcopy(self.violation_types), + "verified_voice_context": deepcopy(self.verified_voice_context), + "is_violating_eu_siep": self.is_violating_eu_siep, "collation_id": self.collation_id, "collation_count": self.collation_count, "collected_at": self.collected_at.isoformat(), @@ -485,6 +547,158 @@ def values(*keys: str) -> list[str]: return TargetingInfo(age_min, age_max, genders, locations, location_types, interests, excluded) + @staticmethod + def _parse_ad_details( + raw: Any, + page: PageInfo | None, + age_gender_dist: list[AudienceDistribution], + region_dist: list[AudienceDistribution], + ) -> dict[str, Any]: + """Normalize the ``ad_details`` payload returned by the details query. + + The payload is the object behind the Ad Library's "See ad details" + panel: advertiser page info, EU/UK/BR transparency (audience, + reach breakdown), US political demographic insights, payer and + beneficiary data and verified-voice context. Fields already set + from the search row are never overwritten; ``age_gender_dist`` and + ``region_dist`` are extended in place only when empty. + """ + empty: dict[str, Any] = { + "page": page, "targeting": None, "beneficiary_payers": [], "ad_details": None, + "eu_transparency": None, "uk_transparency": None, "br_transparency": None, + "eu_total_reach": None, "targets_eu": None, "payer_beneficiary_data": [], + "aaa_info": None, "insights": None, "page_spend": None, "violation_types": [], + "verified_voice_context": None, "is_violating_eu_siep": None, + } + if not isinstance(raw, dict) or not raw: + return empty + result = dict(empty) + result["ad_details"] = deepcopy(raw) + + def block(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + # Advertiser / page information + advertiser = block(raw.get("advertiser")) + library_page = block(advertiser.get("ad_library_page_info")) + page_info = block(library_page.get("page_info")) + about = block(block(advertiser.get("page")).get("about")).get("text") + if page_info or about: + if page is None: + page = PageInfo(id="", name="") + page_id = page_info.get("page_id") or block(advertiser.get("page")).get("id") + if not page.id and page_id is not None: + page.id = str(page_id) + if not page.name and page_info.get("page_name"): + page.name = str(page_info["page_name"]) + if page.likes is None: + page.likes = _numeric_bound(page_info.get("likes")) + if not page.page_url and page_info.get("page_profile_uri"): + page.page_url = page_info["page_profile_uri"] + if not page.profile_picture_url and page_info.get("profile_photo"): + page.profile_picture_url = page_info["profile_photo"] + verification = page_info.get("page_verification") + if isinstance(verification, str) and verification: + page.verification = verification + page.verified = page.verified or verification not in ("NOT_VERIFIED", "UNVERIFIED") + for attribute, key in ( + ("category", "page_category"), ("alias", "page_alias"), ("entity_type", "entity_type"), + ("is_deleted", "page_is_deleted"), ("is_restricted", "page_is_restricted"), + ("is_profile_page", "is_profile_page"), ("cover_photo_url", "page_cover_photo"), + ("ig_username", "ig_username"), ("ig_verified", "ig_verification"), + ): + value = page_info.get(key) + if getattr(page, attribute) in (None, "") and value not in (None, ""): + setattr(page, attribute, value) + if page.ig_followers is None: + page.ig_followers = _numeric_bound(page_info.get("ig_followers")) + if not page.about and isinstance(about, str) and about.strip(): + page.about = about + result["page"] = page + if isinstance(library_page.get("page_spend"), dict): + result["page_spend"] = deepcopy(library_page["page_spend"]) + + # Demographic / regional insights (US political and issue ads) + insights = raw.get("insights") + if isinstance(insights, dict): + result["insights"] = deepcopy(insights) + if not age_gender_dist: + for item in insights.get("age_gender_data") or []: + if not isinstance(item, dict): + continue + age_range = item.get("age_range", "unknown") + for gender in ("female", "male", "unknown"): + value = item.get(gender) + if isinstance(value, bool) or value is None: + continue + try: + age_gender_dist.append(AudienceDistribution(f"{age_range}_{gender}", float(value))) + except (TypeError, ValueError, OverflowError): + continue + if not region_dist: + for item in insights.get("location_data") or []: + if not isinstance(item, dict) or item.get("reach") is None: + continue + try: + region = str(item.get("region", "unknown")) + region_dist.append(AudienceDistribution(region, float(item["reach"]))) + except (TypeError, ValueError, OverflowError): + continue + + # Regional transparency (EU DSA, UK, Brazil) + transparency = block(raw.get("transparency_by_location")) + for key in ("eu_transparency", "uk_transparency", "br_transparency"): + if isinstance(transparency.get(key), dict): + result[key] = deepcopy(transparency[key]) + eu = block(transparency.get("eu_transparency")) + result["eu_total_reach"] = _numeric_bound(eu.get("eu_total_reach")) + if isinstance(eu.get("targets_eu"), bool): + result["targets_eu"] = eu["targets_eu"] + audience = eu or block(transparency.get("uk_transparency")) + if audience: + age = block(audience.get("age_audience")) + gender_audience = audience.get("gender_audience") + locations: list[str] = [] + excluded: list[str] = [] + location_types: list[str] = [] + for item in audience.get("location_audience") or []: + if not isinstance(item, dict) or not item.get("name"): + continue + (excluded if item.get("excluded") else locations).append(str(item["name"])) + if item.get("type") and str(item["type"]) not in location_types: + location_types.append(str(item["type"])) + age_min = _numeric_bound(age.get("min")) + age_max = _numeric_bound(age.get("max")) + genders = [gender_audience] if isinstance(gender_audience, str) and gender_audience else [] + if any((age_min is not None, age_max is not None, genders, locations, excluded)): + result["targeting"] = TargetingInfo( + age_min=age_min, age_max=age_max, genders=genders, locations=locations, + location_types=location_types, excluded_locations=excluded, + ) + + # Payer / beneficiary (EU) and verified voice context + aaa = raw.get("aaa_info") + if isinstance(aaa, dict): + result["aaa_info"] = deepcopy(aaa) + if result["targets_eu"] is None and isinstance(aaa.get("targets_eu"), bool): + result["targets_eu"] = aaa["targets_eu"] + pairs = [item for item in aaa.get("payer_beneficiary_data") or [] if isinstance(item, dict)] + result["payer_beneficiary_data"] = deepcopy(pairs) + names: list[str] = [] + for item in pairs: + for key in ("payer", "beneficiary"): + value = item.get(key) + if isinstance(value, str) and value and value not in names: + names.append(value) + result["beneficiary_payers"] = names + if isinstance(raw.get("violation_types"), list): + result["violation_types"] = deepcopy(raw["violation_types"]) + if raw.get("verified_voice_context") is not None: + result["verified_voice_context"] = deepcopy(raw["verified_voice_context"]) + if isinstance(raw.get("is_violating_eu_siep"), bool): + result["is_violating_eu_siep"] = raw["is_violating_eu_siep"] + return result + @classmethod def from_graphql_response(cls, data: dict[str, Any]) -> Ad: """ @@ -533,7 +747,8 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: name=data.get("page_name", ""), profile_picture_url=data.get("page_profile_picture_url"), page_url=data.get("page_profile_uri"), - likes=data.get("page_like_count"), + likes=_numeric_bound(data.get("page_like_count")), + is_deleted=data.get("page_is_deleted") if isinstance(data.get("page_is_deleted"), bool) else None, ) # Map page_categories to the Ad categories field when present @@ -560,6 +775,12 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: thumbnail_url=card.get("video_preview_image_url"), cta_text=card.get("cta_text") or data.get("cta_text"), cta_type=card.get("cta_type"), + original_image_url=card.get("original_image_url"), + resized_image_url=card.get("resized_image_url"), + watermarked_image_url=card.get("watermarked_resized_image_url"), + watermarked_video_hd_url=card.get("watermarked_video_hd_url"), + watermarked_video_sd_url=card.get("watermarked_video_sd_url"), + image_crops=deepcopy(card.get("image_crops")), ) creatives.append(creative) else: @@ -598,6 +819,12 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: thumbnail_url=video.get("video_preview_image_url"), cta_text=data.get("cta_text"), cta_type=data.get("cta_type"), + original_image_url=image.get("original_image_url"), + resized_image_url=image.get("resized_image_url"), + watermarked_image_url=image.get("watermarked_resized_image_url"), + watermarked_video_hd_url=video.get("watermarked_video_hd_url"), + watermarked_video_sd_url=video.get("watermarked_video_sd_url"), + image_crops=deepcopy(image.get("image_crops")), )) else: # ── Legacy fallback: ad_creative_bodies arrays ────── @@ -649,6 +876,11 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: creative.link_url = card.get("link_url") creative.cta_text = card.get("cta_text") creative.cta_type = card.get("cta_type") + creative.original_image_url = card.get("original_image_url") + creative.resized_image_url = card.get("resized_image_url") + creative.watermarked_image_url = card.get("watermarked_resized_image_url") + creative.watermarked_video_hd_url = card.get("watermarked_video_hd_url") + creative.watermarked_video_sd_url = card.get("watermarked_video_sd_url") # Parse dates delivery_start = None @@ -664,9 +896,17 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: # Parse impressions impressions = None + impressions_text: str | None = None + impressions_index: int | None = None imp_data = _first_present( data, "impressions", "impressionsWithIndex", "impressions_with_index" ) + if isinstance(imp_data, dict): + raw_text = imp_data.get("impressions_text") or imp_data.get("impressionsText") + impressions_text = str(raw_text) if raw_text else None + impressions_index = _numeric_bound(imp_data.get("impressions_index", imp_data.get("impressionsIndex"))) + elif isinstance(imp_data, str) and imp_data.strip(): + impressions_text = imp_data if imp_data is not None: if isinstance(imp_data, str): lower, upper = _parse_impression_text(imp_data) @@ -751,6 +991,17 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: if ad_status_val: is_active = ad_status_val == "ACTIVE" + targeting = cls._parse_targeting(data) + + # ── Ad details payload (AdLibraryV3AdDetailsQuery) ────────── + details = cls._parse_ad_details(data.get("ad_details"), page, age_gender_dist, region_dist) + page = details["page"] + if targeting is None: + targeting = details["targeting"] + beneficiary_payers = data.get("beneficiary_payers") or data.get("beneficiaryPayers") or [] + if not beneficiary_payers: + beneficiary_payers = details["beneficiary_payers"] + return cls( id=str(data.get("id") or data.get("adArchiveID") or data.get("ad_archive_id", "")), ad_library_id=data.get("adLibraryID") or data.get("ad_library_id"), @@ -768,7 +1019,7 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: currency=data.get("currency"), age_gender_distribution=age_gender_dist, region_distribution=region_dist, - targeting=cls._parse_targeting(data), + targeting=targeting, estimated_audience_size_lower=( _numeric_bound(_first_present(data.get("estimated_audience_size", {}), "lower_bound", "lowerBound")) if isinstance(data.get("estimated_audience_size"), dict) else None @@ -787,7 +1038,7 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: disclaimer=_first_present(data, "disclaimer", "disclaimer_label", "disclaimerLabel"), ad_type=data.get("ad_type") or data.get("adType"), categories=data.get("categories") or page_categories, - beneficiary_payers=data.get("beneficiary_payers") or data.get("beneficiaryPayers") or [], + beneficiary_payers=beneficiary_payers, collation_id=_first_present(data, "collation_id", "collationID"), collation_count=_numeric_bound(_first_present(data, "collation_count", "collationCount")), ad_id=( @@ -829,6 +1080,26 @@ def from_graphql_response(cls, data: dict[str, Any]) -> Ad: data, "root_reshared_post", "rootResharedPost" )), fev_info=deepcopy(_first_present(data, "fev_info", "fevInfo")), + page_categories=[str(item) for item in _as_list(data.get("page_categories") or data.get("pageCategories"))], + impressions_text=impressions_text, + impressions_index=impressions_index, + extra_texts=deepcopy(_first_present(data, "extra_texts", "extraTexts")), + extra_links=deepcopy(_first_present(data, "extra_links", "extraLinks")), + extra_images=deepcopy(_first_present(data, "extra_images", "extraImages")), + extra_videos=deepcopy(_first_present(data, "extra_videos", "extraVideos")), + ad_details=details["ad_details"], + eu_transparency=details["eu_transparency"], + uk_transparency=details["uk_transparency"], + br_transparency=details["br_transparency"], + eu_total_reach=details["eu_total_reach"], + targets_eu=details["targets_eu"], + payer_beneficiary_data=details["payer_beneficiary_data"], + aaa_info=details["aaa_info"], + insights=details["insights"], + page_spend=details["page_spend"], + violation_types=details["violation_types"], + verified_voice_context=details["verified_voice_context"], + is_violating_eu_siep=details["is_violating_eu_siep"], raw_data=deepcopy(original_data), ) diff --git a/pyproject.toml b/pyproject.toml index ea5f5fa..e5f119b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "meta-ads-collector" -version = "1.6.0" +version = "1.7.0" description = "Collect ads from the Meta (Facebook) Ad Library -- no API key required" readme = "README.md" license = "MIT" @@ -51,6 +51,7 @@ dev = [ "pytest>=7.0", "pytest-cov>=4.0", "pytest-asyncio>=0.21", + "pytest-rerunfailures>=15", "requests>=2.28.0", "PyYAML>=6.0", "PySocks>=1.7.1", diff --git a/scripts/check_distribution.py b/scripts/check_distribution.py index 1949fd2..75db28a 100644 --- a/scripts/check_distribution.py +++ b/scripts/check_distribution.py @@ -24,6 +24,38 @@ def run(command: list[str], **kwargs) -> None: subprocess.run(command, check=True, **kwargs) +# Live checks reach Meta through a third-party residential proxy. Transport +# failures on that leg (stalled tunnels, CONNECT 590 from the upstream, curl +# timeouts, Meta rate limits) are retried a bounded number of times. Assertion +# failures about Meta's data or the library's behaviour are never retried. +LIVE_TRANSPORT_ERRORS = ( + r"Timeout", + r"timed out", + r"CurlError", + r"CONNECT tunnel", + r"\b590\b", + r"RateLimitError", + r"rate limit", + r"AuthenticationError", + r"SessionExpiredError", + r"Connection error", + r"ConnectionError", + r"ConnectionReset", + r"RemoteDisconnected", + r"Could not resolve", +) +LIVE_RERUNS = 2 +LIVE_RERUN_DELAY_SECONDS = 15 + + +def live_rerun_arguments() -> list[str]: + """pytest-rerunfailures options applied to every actual Meta invocation.""" + arguments = ["--reruns", str(LIVE_RERUNS), "--reruns-delay", str(LIVE_RERUN_DELAY_SECONDS)] + for pattern in LIVE_TRANSPORT_ERRORS: + arguments += ["--only-rerun", pattern] + return arguments + + def private_proxy_values(proxy: str) -> set[str]: """Values to mask in runner output and remove from uploaded evidence.""" values = {proxy} if proxy else set() @@ -71,6 +103,7 @@ def main() -> None: parser.add_argument("--minimum", action="store_true", help="Pin curl-cffi to the declared minimum") parser.add_argument("--live", action="store_true", help="Run actual Meta integration checks") parser.add_argument("--preflight", action="store_true", help="Run only the bounded live connectivity check") + parser.add_argument("--proxy-diagnostics", action="store_true", help="Compare real Meta SOCKS DNS modes") parser.add_argument("--evidence-dir", type=Path, default=Path("ci-results")) args = parser.parse_args() private_values = private_proxy_values(os.environ.get("METAADS_CI_PROXY", "")) @@ -79,6 +112,8 @@ def main() -> None: print("::add-mask::" + value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A"), flush=True) if args.preflight and not args.live: parser.error("--preflight requires --live") + if args.proxy_diagnostics and (not args.live or args.preflight): + parser.error("--proxy-diagnostics requires --live and excludes --preflight") root = Path(__file__).resolve().parents[1] evidence = args.evidence_dir.resolve() evidence.mkdir(parents=True, exist_ok=True) @@ -149,12 +184,18 @@ def main() -> None: env.pop("METAADS_AUDIT_MIN_PYTHON", None) if args.minimum: env["METAADS_AUDIT_MIN_PYTHON"] = str(python) - label = "preflight" if args.preflight else "live" if args.live else "minimum" if args.minimum else "wheel" - target = "tests/test_live_preflight.py" if args.preflight else "tests" + label = "proxy" if args.proxy_diagnostics else ( + "preflight" if args.preflight else "live" if args.live else "minimum" if args.minimum else "wheel" + ) + target = "tests/test_live_proxy_transport.py" if args.proxy_diagnostics else ( + "tests/test_live_preflight.py" if args.preflight else "tests" + ) command = [str(python), "-I", "-m", "pytest", target, "-v", f"--junitxml={evidence / (label + '.xml')}"] if args.live: - command += ["--run-integration", "-m", "integration"] + command += ["--run-integration", "-m", "integration", *live_rerun_arguments()] + if args.proxy_diagnostics: + command += ["-k", "different_python_dns_view or authenticated_socks_proxy", "-o", "junit_family=legacy"] else: command += ["-m", "not integration"] try: diff --git a/tests/README.md b/tests/README.md index b13b77a..81a8e6f 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,5 +1,48 @@ # CI regression cases +## Live transport reruns + +All actual Meta invocations (`scripts/check_distribution.py --live ...` and +`mcp/check_distribution.py --live`) run pytest with `--reruns 2 --reruns-delay 15` +and an `--only-rerun` allowlist of transport failures: curl timeouts, stalled or +refused upstream tunnels (`CONNECT tunnel failed, response 590`), connection +resets, DNS failures, Meta rate limits and bootstrap authentication errors caused +by them. Every other failure (wrong field values, missing ads, library errors) +fails on the first attempt. `test_live_invocations_retry_only_transport_failures` +keeps the two scripts' allowlists identical and checks representative messages. +The live test gateways also retry one stalled upstream attempt within a single +client request (`tests/meta_forward_proxy.py`). + +## SOCKS DNS modes and private CI sessions + +`live-proxy` installs the built wheel outside the checkout and runs all six +SOCKS regression cases before the slower full-suite result is available. Both +`socks5://` (client DNS) and `socks5h://` (proxy DNS) remain real Meta tests. +Related parameter cases share a derived residential session; each test family +has its own session so earlier full-suite traffic does not determine its exit. +Explicit user-selected proxy sessions and other providers are preserved. + +The JUnit `meta_transport` property records actual Meta destination addresses, +HTTP status, numeric GraphQL error codes, and whether an LSD token is present. +It excludes response bodies, error messages, token values, cookies, request +payloads, URL query strings, and proxy credentials. Privacy unit contracts use +an ephemeral canary; integration cases collect actual Meta ads. + +Run the six cases with your private proxy configured: + +```bash +python -m pytest tests/test_live_proxy_transport.py --run-integration -m integration -k "different_python_dns_view or authenticated_socks_proxy" -o junit_family=legacy +``` + +Or verify the distribution built in `dist/`: + +```bash +python scripts/check_distribution.py --live --proxy-diagnostics +``` + +All diagnostics failures block CI. The full live suite still runs the same +cases, and MCP live tests still require the core live suite to pass. + ## Meta media tunnel failures These cases reproduce the two failures in tag CI run diff --git a/tests/ci_network.py b/tests/ci_network.py index 9bc761b..5eea61f 100644 --- a/tests/ci_network.py +++ b/tests/ci_network.py @@ -1,5 +1,6 @@ """Private optional upstream proxy configuration for actual Meta CI traffic.""" +import hashlib import os import uuid from urllib.parse import quote, unquote, urlsplit, urlunsplit @@ -7,6 +8,29 @@ from meta_ads_collector.proxy_pool import parse_proxy +def scoped_ci_proxy(proxy, scope): + """Isolate a live test family while keeping all of its DNS modes on one exit. + + Only our generated Apify sessions are scoped. A user's explicit session or + another proxy provider remains unchanged. Credentials never enter the label. + """ + if not proxy: + return proxy + parsed = urlsplit(parse_proxy(proxy)) + if parsed.hostname != "proxy.apify.com" or not parsed.username: + return proxy + parts = unquote(parsed.username).split(",") + sessions = [part for part in parts if part.startswith("session-")] + if len(sessions) != 1 or not sessions[0].startswith("session-metaads"): + return proxy + suffix = hashlib.sha256(scope.encode("utf-8")).hexdigest()[:12] + session = sessions[0][:44] + suffix + parts[parts.index(sessions[0])] = session + authority = quote(",".join(parts), safe="") + ":" + (parsed.password or "") + authority += "@" + parsed.hostname + (f":{parsed.port}" if parsed.port else "") + return urlunsplit(parsed._replace(netloc=authority)) + + def validate_ci_proxy(proxy, required=False): if required and not proxy: raise ValueError("METAADS_CI_PROXY is required for live GitHub CI checks") diff --git a/tests/meta_detail_samples.py b/tests/meta_detail_samples.py new file mode 100644 index 0000000..589b350 --- /dev/null +++ b/tests/meta_detail_samples.py @@ -0,0 +1,435 @@ +"""Public ``AdLibraryV3AdDetailsQuery`` payloads captured on 2026-10-22T08:11:23.490164+00:00. + +Long audience lists are truncated. No cookies, tokens or request parameters are included. +""" + +import json + +COMMERCIAL_EU_DETAILS: dict = json.loads(r"""{ + "ad_details": { + "aaa_info": { + "has_violating_payer_beneficiary": false, + "is_ad_taken_down": false, + "payer_beneficiary_data": [ + { + "beneficiary": "北京新美互通科技有限公司", + "payer": "北京新美互通科技有限公司" + } + ], + "targets_eu": true + }, + "advertiser": { + "ad_library_page_info": { + "page_info": { + "entity_type": "PERSON_PROFILE", + "ig_followers": null, + "ig_username": null, + "ig_verification": null, + "is_profile_page": false, + "likes": 18627, + "page_alias": "", + "page_category": "Fan Page", + "page_cover_photo": "https://scontent.fcai19-2.fna.fbcdn.net/v/t39.30808-6/352360872_1453605532094233_6700243946456979646_n.png?_nc_cat=104&_nc_map=urlgen_bucketless&ccb=1-7&_nc_sid=957871&_nc_ohc=3gozlSuWmtoQ7kNvwGdBM8k&_nc_oc=AdrwPmXH9t--TJ2R-cyuMooT-P2VoAS0idbN-cbW4AtjstAHQo8Rg7Qp3VLv0cV7HlQ&_nc_zt=23&_nc_ht=scontent.fcai19-2.fna&_nc_gid=izcDDFkH-X1kU8bFVKZU1g&_nc_ss=7b289&oh=00_AQN7ZG_Rt2JcUm76Do8MsfPZfWq797AwGfIlAUghzBBsqQ&oe=6ADF7B2A", + "page_id": "115939511520844", + "page_is_deleted": false, + "page_is_restricted": false, + "page_name": "Perfect themes", + "page_profile_uri": "https://www.facebook.com/100093512920259/", + "page_verification": "NOT_VERIFIED", + "profile_photo": "https://scontent.fcai19-2.fna.fbcdn.net/v/t39.30808-1/352413953_679143790891064_5031911021478074826_n.png?stp=dst-png_s148x148&_nc_cat=106&_nc_map=urlgen_bucketless&ccb=1-7&_nc_sid=418b77&_nc_ohc=Wk7u2oihTisQ7kNvwEONVP7&_nc_oc=AdrM5HjPInVbh8--oJvw7cjmsvDT2ilG3NsIyKEiHhynO1cSdD5MMEjRa3JLJsYmTyo&_nc_zt=24&_nc_ht=scontent.fcai19-2.fna&_nc_gid=izcDDFkH-X1kU8bFVKZU1g&_nc_ss=7b289&oh=00_AQPxe7-fwxc-NSdKHo0LAZZ8iVjHB2a27PKt_AG7BOQfmw&oe=6ADFA620" + }, + "page_spend": { + "current_week": null, + "is_political_page": false, + "lifetime_by_disclaimer": [], + "weekly_by_disclaimer": [] + } + }, + "page": { + "about": { + "text": "ThemePack is a free app with aesthetic app icons, awesome wa..." + }, + "id": "115939511520844", + "is_delegate_page_with_linked_primary_profile": false + } + }, + "is_siep_advertiser_eligible_for_ai_disclosure": true, + "is_violating_eu_siep": false, + "transparency_by_location": { + "br_transparency": null, + "eu_transparency": { + "age_audience": { + "max": 65, + "min": 21 + }, + "age_country_gender_reach_breakdown": [ + { + "age_gender_breakdowns": [ + { + "age_range": "45-54", + "female": 8, + "male": 352, + "unknown": 1 + }, + { + "age_range": "65+", + "female": 3, + "male": 34, + "unknown": 3 + }, + { + "age_range": "55-64", + "female": 2, + "male": 72, + "unknown": 1 + }, + { + "age_range": "18-24", + "female": 19, + "male": 195, + "unknown": 1 + }, + { + "age_range": "35-44", + "female": 37, + "male": 1112, + "unknown": 6 + }, + { + "age_range": "25-34", + "female": 37, + "male": 1044, + "unknown": 2 + } + ], + "country": "PL" + }, + { + "age_gender_breakdowns": [ + { + "age_range": "45-54", + "female": 12, + "male": 209, + "unknown": 3 + }, + { + "age_range": "65+", + "female": 1, + "male": 28, + "unknown": null + }, + { + "age_range": "55-64", + "female": 4, + "male": 63, + "unknown": 1 + }, + { + "age_range": "18-24", + "female": 17, + "male": 176, + "unknown": null + }, + { + "age_range": "35-44", + "female": 25, + "male": 764, + "unknown": 4 + }, + { + "age_range": "25-34", + "female": 37, + "male": 1036, + "unknown": 4 + } + ], + "country": "PT" + } + ], + "eu_total_reach": 48440, + "gender_audience": "All", + "location_audience": [ + { + "excluded": false, + "name": "Guadeloupe", + "num_obfuscated": 0, + "type": "countries" + }, + { + "excluded": false, + "name": "Ireland", + "num_obfuscated": 0, + "type": "countries" + }, + { + "excluded": false, + "name": "Martinique", + "num_obfuscated": 0, + "type": "countries" + } + ], + "targets_eu": true + }, + "uk_transparency": { + "age_audience": { + "max": 65, + "min": 21 + }, + "age_country_gender_reach_breakdown": [ + { + "age_gender_breakdowns": [ + { + "age_range": "45-54", + "female": 9, + "male": 261, + "unknown": 1 + }, + { + "age_range": "65+", + "female": 3, + "male": 32, + "unknown": 1 + }, + { + "age_range": "55-64", + "female": 4, + "male": 84, + "unknown": null + }, + { + "age_range": "25-34", + "female": 52, + "male": 987, + "unknown": 1 + }, + { + "age_range": "18-24", + "female": 24, + "male": 233, + "unknown": 4 + }, + { + "age_range": "35-44", + "female": 32, + "male": 920, + "unknown": 7 + } + ], + "country": "GB" + } + ], + "gender_audience": "All", + "location_audience": [ + { + "excluded": false, + "name": "United Kingdom", + "num_obfuscated": 0, + "type": "countries" + } + ], + "total_reach": 2703 + } + }, + "verified_voice_context": { + "ad_library_all_geo_fin_serv_info": { + "finserv_data": [ + { + "beneficiary_info": { + "license_info": null, + "license_info_list": [], + "location": "CN", + "name": "BEIJING XINMEI HUTONG TECHNOLOGY CO., LTD.", + "website": "https://kikatech.com/" + }, + "geo": "SINGAPORE_UNCATEGORIZED", + "is_payer_beneficiary_same": true, + "payer_info": { + "license_info": null, + "license_info_list": [], + "location": "CN", + "name": "BEIJING XINMEI HUTONG TECHNOLOGY CO., LTD.", + "website": "https://kikatech.com/" + } + } + ] + }, + "types": [ + "UNCATEGORIZED" + ] + }, + "violation_types": [] + }, + "search_row": { + "ad_archive_id": "1550534860016399", + "byline": "", + "categories": [ + "UNKNOWN" + ], + "currency": "", + "disclaimer_label": null, + "end_date": 1792652400, + "impressions_with_index": { + "impressions_index": -1, + "impressions_text": null + }, + "is_aaa_eligible": true, + "is_active": true, + "page_id": "115939511520844", + "page_like_count": 18627, + "page_name": "Perfect themes", + "page_profile_uri": "https://www.facebook.com/100093512920259/", + "publisher_platform": [ + "FACEBOOK", + "INSTAGRAM", + "AUDIENCE_NETWORK", + "MESSENGER", + "THREADS" + ], + "spend": null, + "start_date": 1779174000 + } +}""") + +POLITICAL_US_DETAILS: dict = json.loads(r"""{ + "ad_details": { + "advertiser": { + "ad_library_page_info": { + "page_info": { + "entity_type": "PERSON_PROFILE", + "ig_followers": 7732640, + "ig_username": "facebook", + "ig_verification": true, + "is_profile_page": false, + "likes": 154749669, + "page_alias": "facebook", + "page_category": "Internet company", + "page_cover_photo": "https://scontent.fcai19-2.fna.fbcdn.net/v/t39.99422-6/752509141_1477888607438767_1446725256166483359_n.png?stp=dst-avif&_nc_cat=104&_nc_map=urlgen_bucketless&ccb=1-7&_nc_sid=957871&_nc_ohc=mF5myHbD28MQ7kNvwEhhqNz&_nc_oc=Adpuf-zEyibGw5ILtnmQiALJMPg1tfANINcVNAJNE7wuKWfaXYfpQ1UE6P9K1SGf8OQ&_nc_zt=14&_nc_ht=scontent.fcai19-2.fna&_nc_gid=6UJHhbFk7Jh05Y0dKFsmZA&_nc_ss=7b289&oh=00_AQP-00pYJUFT2j7ozi1nGR1lbBDoA9Lg1r8Qk78PORxqjA&oe=6ADF98A9", + "page_id": "20531316728", + "page_is_deleted": false, + "page_is_restricted": false, + "page_name": "Facebook", + "page_profile_uri": "https://www.facebook.com/facebook/", + "page_verification": "BLUE_VERIFIED", + "profile_photo": "https://scontent.fcai19-2.fna.fbcdn.net/v/t39.30808-1/380700650_10162533193146729_2379134611963304810_n.jpg?stp=dst-jpg_s148x148_tt6&_nc_cat=101&_nc_map=urlgen_bucketless&ccb=1-7&_nc_sid=418b77&_nc_ohc=IKyraUFkNn8Q7kNvwFWqjF-&_nc_oc=AdpUh9Fphl9TMc0RbwzMdDOGDd_NfBTGf7AvY9Am7HO3trSf3ib7QkAFIBDDY9luH44&_nc_zt=24&_nc_ht=scontent.fcai19-2.fna&_nc_gid=6UJHhbFk7Jh05Y0dKFsmZA&_nc_ss=7b289&oh=00_AQNYzzxa3wq2QJkAcarJn7LVJVey2_lhIQJzKaLJH7aQxw&oe=6ADF950E" + }, + "page_spend": { + "current_week": null, + "is_political_page": true, + "lifetime_by_disclaimer": [ + { + "disclaimer": "", + "spend": 921310 + }, + { + "disclaimer": "Facebook, Inc.", + "spend": 30356362 + } + ], + "weekly_by_disclaimer": [] + } + }, + "page": { + "about": { + "text": "" + }, + "id": "20531316728", + "is_delegate_page_with_linked_primary_profile": false + } + }, + "insights": { + "age_gender_data": [ + { + "age_range": "18-24", + "female": 0.11, + "male": 0.08, + "unknown": 0 + }, + { + "age_range": "25-34", + "female": 0.21, + "male": 0.17, + "unknown": 0 + }, + { + "age_range": "35-44", + "female": 0.17, + "male": 0.13, + "unknown": 0 + }, + { + "age_range": "45-54", + "female": 0.07, + "male": 0.05, + "unknown": 0 + } + ], + "currency_matched": true, + "location_data": [ + { + "reach": 0.01, + "region": "South Carolina" + }, + { + "reach": 0.01, + "region": "Minnesota" + }, + { + "reach": 0.01, + "region": "Massachusetts" + }, + { + "reach": 0.01, + "region": "Maryland" + }, + { + "reach": 0.01, + "region": "Louisiana" + }, + { + "reach": 0.01, + "region": "Kentucky" + } + ], + "single_country": "US" + }, + "is_siep_advertiser_eligible_for_ai_disclosure": true, + "is_violating_eu_siep": false, + "transparency_by_location": { + "br_transparency": null, + "eu_transparency": null, + "uk_transparency": null + }, + "verified_voice_context": { + "ad_library_all_geo_fin_serv_info": null, + "types": [ + "POLITICAL" + ] + }, + "violation_types": [] + }, + "search_row": { + "ad_archive_id": "352695862528588", + "byline": "Facebook, Inc.", + "categories": [ + "POLITICAL" + ], + "currency": "USD", + "disclaimer_label": "PAID_FOR_BY", + "end_date": 1598770800, + "impressions_with_index": { + "impressions_index": 39, + "impressions_text": ">1M" + }, + "is_aaa_eligible": false, + "is_active": false, + "page_id": "20531316728", + "page_like_count": 154749669, + "page_name": "Facebook", + "page_profile_uri": "https://www.facebook.com/facebook/", + "publisher_platform": [ + "FACEBOOK" + ], + "spend": ">$1M", + "start_date": 1598511600 + } +}""") diff --git a/tests/meta_forward_proxy.py b/tests/meta_forward_proxy.py index 2276ad6..798e4e3 100644 --- a/tests/meta_forward_proxy.py +++ b/tests/meta_forward_proxy.py @@ -27,15 +27,37 @@ def _is_meta_host(host): return name == "facebook.com" or name.endswith((".facebook.com", ".fbcdn.net")) +# A residential upstream occasionally stalls while it opens its own leg to +# Meta. Give each upstream attempt a bounded budget and retry once so one +# stalled connection stays inside the client's 30 s request timeout. +UPSTREAM_ATTEMPTS = 2 +UPSTREAM_ATTEMPT_TIMEOUT = 14 +RELAY_TIMEOUT = 30 + + def _connect_remote(host, port, upstream, server_name=None): """Open an opaque Meta tunnel, optionally through a private CI proxy.""" if not upstream: - return socket.create_connection((host, port), timeout=30) + return socket.create_connection((host, port), timeout=RELAY_TIMEOUT) + failure = None + for _attempt in range(UPSTREAM_ATTEMPTS): + try: + remote = _connect_upstream_once(host, port, upstream, server_name, UPSTREAM_ATTEMPT_TIMEOUT) + except OSError as exc: + failure = exc + continue + remote.settimeout(RELAY_TIMEOUT) + return remote + raise OSError(f"Upstream proxy did not open a Meta tunnel in {UPSTREAM_ATTEMPTS} attempts") from failure + + +def _connect_upstream_once(host, port, upstream, server_name, timeout): + """One bounded attempt to open the tunnel through the configured upstream proxy.""" proxy = urlsplit(upstream) username = unquote(proxy.username) if proxy.username is not None else None password = unquote(proxy.password) if proxy.password is not None else None if proxy.scheme in {"http", "https"}: - remote = socket.create_connection((proxy.hostname, proxy.port), timeout=30) + remote = socket.create_connection((proxy.hostname, proxy.port), timeout=timeout) try: if proxy.scheme == "https": import certifi @@ -73,7 +95,7 @@ def _connect_remote(host, port, upstream, server_name=None): remote.set_proxy(kind, proxy.hostname, proxy.port, rdns=proxy.scheme in {"socks4a", "socks5h"}, username=username, password=password) - remote.settimeout(30) + remote.settimeout(timeout) remote.connect((host, port)) return remote except Exception: diff --git a/tests/meta_transport_diagnostics.py b/tests/meta_transport_diagnostics.py new file mode 100644 index 0000000..c686ab0 --- /dev/null +++ b/tests/meta_transport_diagnostics.py @@ -0,0 +1,64 @@ +"""Allowlisted metadata from real Meta responses; never cookies, tokens or bodies.""" + +from __future__ import annotations + +import inspect +import json +from urllib.parse import urlsplit + + +def response_metadata(client, method, url, response): + """Do not serialize server messages, URLs, request arguments or credentials.""" + parsed = urlsplit(url) + if parsed.hostname not in {"www.facebook.com", "web.facebook.com"}: + return None + codes = [] + if parsed.path == "/api/graphql/": + try: + text = response.text + payload = json.loads(text[9:] if text.startswith("for (;;);") else text) + if isinstance(payload, dict): + for error in payload.get("errors", []) or []: + if isinstance(error, dict) and type(error.get("code")) is int: + codes.append(error["code"]) + except (ValueError, TypeError): + pass + return { + "method": "POST" if method.upper() == "POST" else "GET", + "endpoint": "graphql" if parsed.path == "/api/graphql/" else "bootstrap", + "host": parsed.hostname, + "status": int(response.status_code), + "error_codes": codes, + "lsd_present": bool(getattr(client, "_tokens", {}).get("lsd")), + } + + +class MetaTransportDiagnostics: + """Observe the existing request method without changing any network behavior.""" + + def __init__(self): + self.responses = [] + + def instrument(self, patch, client): + request = client._make_request + + def record(method, url, response): + entry = response_metadata(client, method, url, response) + if entry is not None and len(self.responses) < 100: + self.responses.append(entry) + + if inspect.iscoroutinefunction(request): + async def async_request(method, url, **kwargs): + response = await request(method, url, **kwargs) + record(method, url, response) + return response + patch.setattr(client, "_make_request", async_request) + else: + def sync_request(method, url, **kwargs): + response = request(method, url, **kwargs) + record(method, url, response) + return response + patch.setattr(client, "_make_request", sync_request) + + def snapshot(self, destinations): + return {"responses": list(self.responses), "meta_destinations": sorted(set(destinations))} diff --git a/tests/test_ad_details.py b/tests/test_ad_details.py new file mode 100644 index 0000000..fc35aa6 --- /dev/null +++ b/tests/test_ad_details.py @@ -0,0 +1,467 @@ +"""The ``AdLibraryV3AdDetailsQuery`` payload: parsing, enrichment, client composition and export.""" + +from __future__ import annotations + +import csv +import json +import time +from copy import deepcopy +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from meta_ads_collector.async_client import AsyncMetaAdsClient +from meta_ads_collector.client import MetaAdsClient, parse_ad_details_response +from meta_ads_collector.collector import MetaAdsCollector +from meta_ads_collector.constants import DOC_ID_AD_DETAILS +from meta_ads_collector.exceptions import MetaAdsError, RateLimitError +from meta_ads_collector.exports import CSV_COLUMNS, ad_to_csv_row +from meta_ads_collector.models import Ad, PageInfo + +from .meta_detail_samples import COMMERCIAL_EU_DETAILS, POLITICAL_US_DETAILS + + +def _combined(sample: dict) -> dict: + data = deepcopy(sample["search_row"]) + data["ad_details"] = deepcopy(sample["ad_details"]) + return data + + +def _graphql_reply(details, errors=None) -> dict: + reply: dict = {"data": {"ad_library_main": {"ad_details": details}}, "extensions": {"is_final": True}} + if errors is not None: + reply["errors"] = errors + return reply + + +# --------------------------------------------------------------------------- +# Model parsing +# --------------------------------------------------------------------------- + + +def test_commercial_eu_details_populate_transparency_targeting_and_payers(): + data = _combined(COMMERCIAL_EU_DETAILS) + details = COMMERCIAL_EU_DETAILS["ad_details"] + eu = details["transparency_by_location"]["eu_transparency"] + ad = Ad.from_graphql_response(data) + + assert ad.ad_details == details + assert ad.eu_transparency == eu + assert ad.uk_transparency == details["transparency_by_location"]["uk_transparency"] + assert ad.br_transparency is None + assert ad.eu_total_reach == eu["eu_total_reach"] + assert ad.targets_eu is True + assert ad.targeting is not None + assert ad.targeting.age_min == eu["age_audience"]["min"] + assert ad.targeting.age_max == eu["age_audience"]["max"] + assert ad.targeting.genders == [eu["gender_audience"]] + assert ad.targeting.locations == [item["name"] for item in eu["location_audience"] if not item["excluded"]] + assert ad.targeting.excluded_locations == [item["name"] for item in eu["location_audience"] if item["excluded"]] + expected_types: list[str] = [] + for item in eu["location_audience"]: + if item["type"] not in expected_types: + expected_types.append(item["type"]) + assert ad.targeting.location_types == expected_types + assert ad.payer_beneficiary_data == details["aaa_info"]["payer_beneficiary_data"] + assert ad.aaa_info == details["aaa_info"] + expected_names: list[str] = [] + for item in details["aaa_info"]["payer_beneficiary_data"]: + for key in ("payer", "beneficiary"): + if item[key] not in expected_names: + expected_names.append(item[key]) + assert ad.beneficiary_payers == expected_names + assert ad.verified_voice_context == details["verified_voice_context"] + assert ad.violation_types == details["violation_types"] + assert ad.is_violating_eu_siep is details["is_violating_eu_siep"] + assert ad.page_spend == details["advertiser"]["ad_library_page_info"]["page_spend"] + + +def test_details_fill_advertiser_page_fields_without_overwriting_search_row_values(): + data = _combined(COMMERCIAL_EU_DETAILS) + page_info = COMMERCIAL_EU_DETAILS["ad_details"]["advertiser"]["ad_library_page_info"]["page_info"] + data["page_like_count"] = page_info["likes"] + 5 # the search row wins for shared fields + ad = Ad.from_graphql_response(data) + + assert ad.page is not None + assert ad.page.id == data["page_id"] + assert ad.page.name == data["page_name"] + assert ad.page.likes == page_info["likes"] + 5 + assert ad.page.verification == page_info["page_verification"] + assert ad.page.verified is (page_info["page_verification"] != "NOT_VERIFIED") + assert ad.page.category == page_info["page_category"] + assert ad.page.entity_type == page_info["entity_type"] + assert ad.page.is_restricted is page_info["page_is_restricted"] + assert ad.page.cover_photo_url == page_info["page_cover_photo"] + assert ad.page.profile_picture_url == page_info["profile_photo"] + assert ad.page.about == COMMERCIAL_EU_DETAILS["ad_details"]["advertiser"]["page"]["about"]["text"] + + +def test_political_details_build_audience_distributions_from_insights(): + data = _combined(POLITICAL_US_DETAILS) + insights = POLITICAL_US_DETAILS["ad_details"]["insights"] + page_info = POLITICAL_US_DETAILS["ad_details"]["advertiser"]["ad_library_page_info"]["page_info"] + ad = Ad.from_graphql_response(data) + + assert ad.insights == insights + expected_rows = sum( + 1 for item in insights["age_gender_data"] for gender in ("female", "male", "unknown") + if item.get(gender) is not None + ) + assert len(ad.age_gender_distribution) == expected_rows + first = insights["age_gender_data"][0] + assert ad.age_gender_distribution[0].category == f"{first['age_range']}_female" + assert ad.age_gender_distribution[0].percentage == pytest.approx(first["female"]) + regions = [item["region"] for item in insights["location_data"]] + assert [entry.category for entry in ad.region_distribution] == regions + assert ad.page is not None + assert ad.page.verified is True + assert ad.page.verification == "BLUE_VERIFIED" + assert ad.page.ig_username == page_info["ig_username"] + assert ad.page.ig_followers == page_info["ig_followers"] + assert ad.page.ig_verified is page_info["ig_verification"] + assert ad.page.alias == page_info["page_alias"] + assert ad.eu_transparency is None + assert ad.eu_total_reach is None + assert ad.bylines == [data["byline"]] + assert ad.disclaimer == data["disclaimer_label"] + assert ad.impressions_text == data["impressions_with_index"]["impressions_text"] + assert ad.impressions_index == data["impressions_with_index"]["impressions_index"] + + +def test_details_only_payload_builds_page_from_advertiser_block(): + details = deepcopy(COMMERCIAL_EU_DETAILS["ad_details"]) + page_info = details["advertiser"]["ad_library_page_info"]["page_info"] + ad = Ad.from_graphql_response({"ad_archive_id": "42", "page_id": page_info["page_id"], "ad_details": details}) + + assert ad.id == "42" + assert ad.page is not None + assert ad.page.id == page_info["page_id"] + assert ad.page.name == page_info["page_name"] + assert ad.page.likes == page_info["likes"] + assert ad.page.page_url == page_info["page_profile_uri"] + assert all(creative.to_dict() == {} for creative in ad.creatives) # no creative content without a row + + +def test_details_parsing_is_lossless_and_does_not_mutate_input(): + data = _combined(COMMERCIAL_EU_DETAILS) + snapshot = deepcopy(data) + ad = Ad.from_graphql_response(data) + + assert data == snapshot + assert ad.api_fields == snapshot + exported = json.loads(ad.to_json()) + assert exported["api_fields"] == snapshot + assert exported["ad_details"] == snapshot["ad_details"] + assert exported["eu_total_reach"] == ad.eu_total_reach + assert exported["payer_beneficiary_data"] == ad.payer_beneficiary_data + assert exported["page"]["verification"] == ad.page.verification + ad.ad_details["advertiser"] = None + assert ad.api_fields["ad_details"]["advertiser"] is not None + + +@pytest.mark.parametrize("value", [None, {}, [], "text", 5]) +def test_absent_or_malformed_details_leave_search_row_parsing_unchanged(value): + data = deepcopy(COMMERCIAL_EU_DETAILS["search_row"]) + baseline = Ad.from_graphql_response(deepcopy(data)) + data["ad_details"] = value + ad = Ad.from_graphql_response(data) + assert ad.ad_details is None + assert ad.eu_transparency is None + assert ad.targeting is None + assert ad.page == baseline.page + assert ad.payer_beneficiary_data == [] + assert ad.api_fields == data + + +def test_partial_details_tolerate_missing_sections(): + details = {"advertiser": {"page": {"id": "9", "about": {"text": ""}}}, "insights": None, + "transparency_by_location": None, "aaa_info": None, "violation_types": None} + ad = Ad.from_graphql_response({"ad_archive_id": "1", "page_id": "9", "ad_details": details}) + assert ad.ad_details == details + assert ad.page is not None and ad.page.id == "9" + assert ad.insights is None + assert ad.violation_types == [] + assert ad.targeting is None + + +# --------------------------------------------------------------------------- +# Enrichment merges detail fields into sparse ads +# --------------------------------------------------------------------------- + + +def test_enrich_ad_fills_detail_fields_and_preserves_original(): + collector = MetaAdsCollector.__new__(MetaAdsCollector) + collector.client = MagicMock() + collector.client.get_ad_details.return_value = _combined(COMMERCIAL_EU_DETAILS) + row = COMMERCIAL_EU_DETAILS["search_row"] + sparse = Ad(id=row["ad_archive_id"], page=PageInfo(id=row["page_id"], name="")) + + enriched = collector.enrich_ad(sparse) + + assert enriched is not sparse + assert sparse.page.name == "" and sparse.ad_details is None + assert enriched.page.name == row["page_name"] + assert enriched.eu_total_reach == COMMERCIAL_EU_DETAILS["ad_details"]["transparency_by_location"][ + "eu_transparency"]["eu_total_reach"] + assert enriched.targeting is not None and enriched.targeting.age_min is not None + assert enriched.payer_beneficiary_data + assert enriched.ad_details == COMMERCIAL_EU_DETAILS["ad_details"] + assert enriched.raw_data["ad_details"] == COMMERCIAL_EU_DETAILS["ad_details"] + collector.client.get_ad_details.assert_called_once_with(ad_archive_id=row["ad_archive_id"], page_id=row["page_id"]) + + +# --------------------------------------------------------------------------- +# Client composition +# --------------------------------------------------------------------------- + + +def _sync_client(search_rows, reply, status=200): + client = MetaAdsClient.__new__(MetaAdsClient) + client._initialized = True + client._doc_ids = {} + client._tokens = {"lsd": "lsd-token", "x-asbd-id": "359341"} + client._fingerprint = MagicMock() + client._fingerprint.get_graphql_headers.return_value = {"content-type": "application/x-www-form-urlencoded"} + client._fingerprint.get_default_headers.return_value = {} + client._consecutive_errors = 3 + client._init_time = time.time() + client._max_session_age = 1800 + captured: dict = {} + + def build(doc_id, variables, friendly_name): + captured.update(doc_id=doc_id, variables=variables, friendly_name=friendly_name) + return {"doc_id": doc_id, "variables": json.dumps(variables)} + + client._build_graphql_payload = build + client.search_ads = MagicMock(return_value=({"ads": search_rows}, None)) + client._make_graphql_request = MagicMock( + return_value=MagicMock(status_code=status, text="for (;;);" + json.dumps(reply)), + ) + client._make_request = MagicMock(return_value=MagicMock(status_code=403, text="")) + return client, captured + + +def test_get_ad_insights_sends_the_details_query_and_returns_the_payload(): + details = COMMERCIAL_EU_DETAILS["ad_details"] + client, captured = _sync_client([], _graphql_reply(details)) + + result = client.get_ad_insights("123", "456") + + assert result == details + assert captured["doc_id"] == DOC_ID_AD_DETAILS + assert captured["friendly_name"] == "AdLibraryV3AdDetailsQuery" + variables = captured["variables"] + assert variables["adArchiveID"] == "123" and variables["pageID"] == "456" + assert variables["country"] == "ALL" + assert variables["isAdNonPolitical"] is False and variables["isAdNotAAAEligible"] is False + assert variables["sessionID"] + headers = client._make_graphql_request.call_args.args[1] + assert headers["x-fb-friendly-name"] == "AdLibraryV3AdDetailsQuery" + assert headers["x-fb-lsd"] == "lsd-token" + assert headers["referer"].endswith("?id=123") + assert client._consecutive_errors == 0 + + +def test_get_ad_insights_prefers_a_dynamically_extracted_doc_id(): + client, captured = _sync_client([], _graphql_reply(COMMERCIAL_EU_DETAILS["ad_details"])) + client._doc_ids = {"AdLibraryV3AdDetailsQuery": "999"} + client.get_ad_insights("1", "2", country="DE") + assert captured["doc_id"] == "999" + assert captured["variables"]["country"] == "DE" + + +def test_get_ad_insights_raises_when_meta_returns_no_details(): + client, _ = _sync_client([], _graphql_reply(None, errors=[{"message": "field_exception", "code": 1}])) + with pytest.raises(MetaAdsError, match="field_exception"): + client.get_ad_insights("1", "2") + + +def test_get_ad_insights_raises_rate_limit_error(): + client, _ = _sync_client([], _graphql_reply(None, errors=[{"message": "Rate limit exceeded", "code": 1675004}])) + with pytest.raises(RateLimitError): + client.get_ad_insights("1", "2") + + +def test_get_ad_insights_raises_on_http_error(): + client, _ = _sync_client([], {}, status=500) + with pytest.raises(MetaAdsError, match="500"): + client.get_ad_insights("1", "2") + + +def test_parse_ad_details_response_keeps_partial_payloads_with_field_errors(): + details = {"advertiser": {"page": {"id": "1"}}, "insights": None} + reply = _graphql_reply(details, errors=[{"message": "field_exception", "code": 1}]) + assert parse_ad_details_response(reply, "1") == details + with pytest.raises(MetaAdsError): + parse_ad_details_response({"data": None}, "1") + with pytest.raises(MetaAdsError): + parse_ad_details_response("not json", "1") + + +def test_get_ad_details_combines_search_row_and_details(): + row = deepcopy(COMMERCIAL_EU_DETAILS["search_row"]) + details = COMMERCIAL_EU_DETAILS["ad_details"] + client, _ = _sync_client([{"ad_archive_id": "other"}, row], _graphql_reply(details)) + + result = client.get_ad_details(row["ad_archive_id"], page_id=row["page_id"]) + + assert result == {**row, "ad_details": details} + assert client.search_ads.call_args.kwargs["page_ids"] == [row["page_id"]] + assert client._make_request.call_count == 0 # the HTML fallback is not needed + + +def test_get_ad_details_returns_details_when_the_row_is_not_in_the_page_search(): + details = COMMERCIAL_EU_DETAILS["ad_details"] + client, _ = _sync_client([{"ad_archive_id": "other"}], _graphql_reply(details)) + result = client.get_ad_details("123", page_id="456") + assert result == {"ad_archive_id": "123", "page_id": "456", "ad_details": details} + ad = Ad.from_graphql_response(result) + assert ad.page.name == details["advertiser"]["ad_library_page_info"]["page_info"]["page_name"] + + +def test_get_ad_details_returns_the_row_when_the_details_query_fails(): + row = deepcopy(COMMERCIAL_EU_DETAILS["search_row"]) + client, _ = _sync_client([row], _graphql_reply(None, errors=[{"message": "down", "code": 2}])) + assert client.get_ad_details(row["ad_archive_id"], page_id=row["page_id"]) == row + + +def test_get_ad_details_without_page_id_falls_back_to_the_html_page(): + client, _ = _sync_client([], _graphql_reply(COMMERCIAL_EU_DETAILS["ad_details"])) + with pytest.raises(NotImplementedError): + client.get_ad_details("123") + client.search_ads.assert_not_called() + client._make_graphql_request.assert_not_called() + assert client._make_request.call_count == 1 + + +def test_get_ad_details_raises_when_every_approach_fails(): + client, _ = _sync_client([], _graphql_reply(None, errors=[{"message": "down", "code": 2}])) + client.search_ads.side_effect = MetaAdsError("search down") + with pytest.raises(NotImplementedError): + client.get_ad_details("123", page_id="456") + + +def _async_client(search_rows, reply, status=200): + client = AsyncMetaAdsClient.__new__(AsyncMetaAdsClient) + client._initialized = True + client._doc_ids = {} + client._tokens = {"lsd": "lsd-token"} + client._fingerprint = MagicMock() + client._fingerprint.get_graphql_headers.return_value = {} + client._fingerprint.get_default_headers.return_value = {} + captured: dict = {} + + def build(doc_id, variables, friendly_name): + captured.update(doc_id=doc_id, variables=variables, friendly_name=friendly_name) + return {"doc_id": doc_id} + + client._build_graphql_payload = build + client.search_ads = AsyncMock(return_value=({"ads": search_rows}, None)) + graphql = MagicMock(status_code=status, text="for (;;);" + json.dumps(reply)) + html = MagicMock(status_code=403, text="") + + async def request(method, url, **kwargs): + return graphql if method == "POST" else html + + client._make_request = AsyncMock(side_effect=request) + return client, captured + + +@pytest.mark.asyncio +async def test_async_get_ad_details_combines_search_row_and_details(): + row = deepcopy(COMMERCIAL_EU_DETAILS["search_row"]) + details = COMMERCIAL_EU_DETAILS["ad_details"] + client, captured = _async_client([row], _graphql_reply(details)) + + result = await client.get_ad_details(row["ad_archive_id"], page_id=row["page_id"]) + + assert result == {**row, "ad_details": details} + assert captured["doc_id"] == DOC_ID_AD_DETAILS + assert captured["variables"]["adArchiveID"] == row["ad_archive_id"] + assert captured["variables"]["pageID"] == row["page_id"] + assert client._make_request.await_count == 1 + + +@pytest.mark.asyncio +async def test_async_get_ad_insights_raises_on_missing_details(): + client, _ = _async_client([], _graphql_reply(None, errors=[{"message": "nope", "code": 3}])) + with pytest.raises(MetaAdsError, match="nope"): + await client.get_ad_insights("1", "2") + + +@pytest.mark.asyncio +async def test_async_get_ad_details_raises_when_every_approach_fails(): + client, _ = _async_client([], _graphql_reply(None, errors=[{"message": "nope", "code": 3}])) + with pytest.raises(NotImplementedError): + await client.get_ad_details("1", page_id="2") + + +# --------------------------------------------------------------------------- +# CSV export of the flattened schema +# --------------------------------------------------------------------------- + + +def test_csv_row_matches_the_shared_columns_and_exposes_detail_fields(tmp_path): + ad = Ad.from_graphql_response(_combined(COMMERCIAL_EU_DETAILS)) + row = ad_to_csv_row(ad) + + assert tuple(row) == CSV_COLUMNS + assert row["eu_total_reach"] == ad.eu_total_reach + assert row["page_like_count"] == ad.page.likes + assert row["payer_beneficiary"] == ";".join( + f"{item['payer']}|{item['beneficiary']}" for item in ad.payer_beneficiary_data + ) + assert json.loads(row["api_fields"]) == ad.api_fields + + path = tmp_path / "details.csv" + with path.open("w", newline="", encoding="utf-8") as stream: + writer = csv.DictWriter(stream, fieldnames=list(CSV_COLUMNS)) + writer.writeheader() + writer.writerow(row) + with path.open(encoding="utf-8", newline="") as stream: + reader = csv.DictReader(stream) + rows = list(reader) + assert reader.fieldnames == list(CSV_COLUMNS) + assert json.loads(rows[0]["api_fields"])["ad_details"] == COMMERCIAL_EU_DETAILS["ad_details"] + + +def test_csv_row_blanks_missing_values(): + row = ad_to_csv_row(Ad(id="1")) + assert tuple(row) == CSV_COLUMNS + assert row["page_like_count"] == "" and row["eu_total_reach"] == "" and row["payer_beneficiary"] == "" + assert row["api_fields"] == "null" + + +# --------------------------------------------------------------------------- +# Live checks against the real Ad Library +# --------------------------------------------------------------------------- + + +@pytest.mark.integration +def test_live_ad_insights_return_the_details_panel_for_an_actual_ad(collected_ads): + source = next(ad for ad in collected_ads if ad.page and ad.page.id and ad.raw_data) + with MetaAdsClient(timeout=30, max_retries=2) as client: + details = client.get_ad_insights(source.id, source.page.id) + page_info = details["advertiser"]["ad_library_page_info"]["page_info"] + assert page_info["page_id"] == source.page.id + assert page_info["page_name"] + assert "transparency_by_location" in details and "aaa_info" in details + + enriched = Ad.from_graphql_response({**deepcopy(source.raw_data), "ad_details": details}) + assert enriched.ad_details == details + assert enriched.page.verification + assert enriched.page.category or enriched.page.about or enriched.page.likes is not None + assert enriched.to_dict()["api_fields"]["ad_details"] == details + if enriched.eu_transparency: + assert enriched.targeting is not None + assert enriched.eu_total_reach == enriched.eu_transparency.get("eu_total_reach") + + +@pytest.mark.integration +@pytest.mark.asyncio +async def test_live_async_ad_insights_match_the_sync_payload_shape(collected_ads): + source = next(ad for ad in collected_ads if ad.page and ad.page.id) + async with AsyncMetaAdsClient(timeout=30, max_retries=2) as client: + details = await client.get_ad_insights(source.id, source.page.id) + assert details["advertiser"]["ad_library_page_info"]["page_info"]["page_id"] == source.page.id + assert set(details) >= {"advertiser", "transparency_by_location", "violation_types"} diff --git a/tests/test_audit_live_collection.py b/tests/test_audit_live_collection.py index 1f0f3da..4006a9e 100644 --- a/tests/test_audit_live_collection.py +++ b/tests/test_audit_live_collection.py @@ -153,7 +153,7 @@ def test_live_enrichment_preserves_identity_for_an_actually_returned_ad( "delivery_stop_time", "snapshot_url", "ad_snapshot_url", "impressions", "spend", "reach", "currency", "estimated_audience_size_lower", "estimated_audience_size_upper", "funding_entity", "disclaimer", "ad_type", - "targeting", + "targeting", "ad_details", "eu_transparency", "eu_total_reach", "insights", "page_spend", ) list_fields = ( "publisher_platforms", "languages", "categories", "bylines", @@ -170,7 +170,7 @@ def test_live_enrichment_preserves_identity_for_an_actually_returned_ad( if source.page is None and details.page and details.page.id: candidates["page"] = details.page elif source.page and details.page: - for field_name in ("profile_picture_url", "page_url", "likes"): + for field_name in ("profile_picture_url", "page_url", "likes", "verification", "category", "about"): detail_value = getattr(details.page, field_name) if getattr(source.page, field_name) in (None, "", 0) and detail_value: candidates[f"page.{field_name}"] = detail_value diff --git a/tests/test_audit_live_io.py b/tests/test_audit_live_io.py index d76997e..b092b10 100644 --- a/tests/test_audit_live_io.py +++ b/tests/test_audit_live_io.py @@ -31,6 +31,13 @@ def _one_live_thumbnail_or_image(collected_ads): pytest.skip("Meta returned no image or thumbnail for this live sample") +def _retry_urls(url): + """The creative URL plus its generic Meta CDN host alternate used on odd retries.""" + from meta_ads_collector.media import fallback_media_url + + return {url, fallback_media_url(url) or url} + + def _inject_initial_connect_failures(downloader, monkeypatch, failures): """Record every attempt; after controlled failures delegate to real Meta.""" from curl_cffi.requests.exceptions import ConnectionError @@ -61,7 +68,7 @@ def test_live_relative_media_directory_reports_an_absolute_path(tmp_path, monkey downloader.session.close() assert result.success, result.error assert failures + 1 <= len(requests) <= downloader.max_retries - assert all(url == ad.creatives[0].image_url for url in requests) + assert all(url in _retry_urls(ad.creatives[0].image_url) for url in requests) assert result.local_path is not None assert Path(result.local_path).is_absolute() assert Path(result.local_path).is_relative_to((tmp_path / "relative-live-media").resolve()) @@ -81,7 +88,7 @@ def test_live_meta_media_with_controlled_proxy_connect_590_is_bounded( result = downloader.download_ad_media(ad)[0] finally: downloader.session.close() - assert all(url == ad.creatives[0].image_url for url in requests) + assert all(url in _retry_urls(ad.creatives[0].image_url) for url in requests) assert len(requests) <= downloader.max_retries if failures < downloader.max_retries: assert failures + 1 <= len(requests) diff --git a/tests/test_audit_live_surface.py b/tests/test_audit_live_surface.py index 0a48ff6..ce31faa 100644 --- a/tests/test_audit_live_surface.py +++ b/tests/test_audit_live_surface.py @@ -21,7 +21,7 @@ @pytest.fixture(scope="module") def surface_client(): - with MetaAdsClient(timeout=20, max_retries=2) as client: + with MetaAdsClient(timeout=30, max_retries=3) as client: client.initialize() yield client @@ -72,7 +72,7 @@ def test_live_keyword_and_sort_modes(surface_client, search_type, sort): def test_live_stress_collection_paginates_and_deduplicates(record_property): """Exercise bounded real pagination while respecting request delays.""" - with MetaAdsCollector(timeout=20, max_retries=2, rate_limit_delay=1, jitter=0.3) as collector: + with MetaAdsCollector(timeout=30, max_retries=3, rate_limit_delay=1, jitter=0.3) as collector: tracker = DeduplicationTracker() ads = list(collector.search(query="nike", country="US", max_results=120, page_size=10, dedup_tracker=tracker)) diff --git a/tests/test_audit_packaging.py b/tests/test_audit_packaging.py index 838f673..a0e8303 100644 --- a/tests/test_audit_packaging.py +++ b/tests/test_audit_packaging.py @@ -63,6 +63,7 @@ def test_published_sdist_includes_support_for_the_tests_it_ships(tmp_path): required = { "tests/__init__.py", "tests/utils.py", "tests/conftest.py", "tests/audit_meta_samples.py", "tests/meta_full_sample.py", "tests/meta_forward_proxy.py", "tests/ci_network.py", + "tests/meta_transport_diagnostics.py", "tests/test_all_meta_fields.py", "tests/test_live_proxy_transport.py", "scripts/check_distribution.py", "tests/README.md", ".github/workflows/ci.yml", ".github/workflows/publish.yml", diff --git a/tests/test_ci_configuration.py b/tests/test_ci_configuration.py index 2d520c0..3731f34 100644 --- a/tests/test_ci_configuration.py +++ b/tests/test_ci_configuration.py @@ -1,21 +1,31 @@ """Regression contracts for the actual branch, release and private live CI configuration.""" import os +import re import tarfile from pathlib import Path import yaml -def workflow(name): - relative = f".github/workflows/{name}.yml" +def repository_text(relative): sdist = os.environ.get("METAADS_AUDIT_SDIST") if sdist: with tarfile.open(sdist) as archive: member, = [member for member in archive.getmembers() if member.name.endswith("/" + relative)] - content = archive.extractfile(member).read().decode("utf-8") - else: - content = (Path(__file__).resolve().parents[1] / relative).read_text(encoding="utf-8") + return archive.extractfile(member).read().decode("utf-8") + return (Path(__file__).resolve().parents[1] / relative).read_text(encoding="utf-8") + + +def script_namespace(relative): + namespace = {"__name__": "check_distribution_under_test"} + exec(compile(repository_text(relative), relative, "exec"), namespace) + return namespace + + +def workflow(name): + relative = f".github/workflows/{name}.yml" + content = repository_text(relative) # BaseLoader preserves the GitHub event key 'on', which YAML 1.1 otherwise # interprets as a boolean. These contracts intentionally compare scalar strings. return yaml.load(content, Loader=yaml.BaseLoader) @@ -40,7 +50,7 @@ def test_published_releases_keep_full_validation_and_private_proxy_forwarding(): def test_live_failures_remain_blocking_and_mcp_live_runs_after_core_live(): jobs = workflow("ci")["jobs"] - for name in ("live-connectivity", "live-meta", "mcp-live"): + for name in ("live-connectivity", "live-proxy", "live-meta", "mcp-live"): job = jobs[name] assert job.get("continue-on-error", "false") == "false" assert job["env"]["METAADS_CI_PROXY"] == "${{ secrets.METAADS_CI_PROXY }}" @@ -50,9 +60,43 @@ def test_live_failures_remain_blocking_and_mcp_live_runs_after_core_live(): assert any("scripts/check_distribution.py --live" in step.get("run", "") for step in jobs["live-meta"]["steps"]) +def test_sock_dns_diagnostics_run_on_actual_distribution_and_remain_blocking(): + job = workflow("ci")["jobs"]["live-proxy"] + assert job["needs"] == ["distribution"] + assert job["runs-on"] == "macos-latest" + assert any("--live --proxy-diagnostics" in step.get("run", "") for step in job["steps"]) + upload = [step for step in job["steps"] if step.get("uses", "").startswith("actions/upload-artifact")] + assert len(upload) == 1 and upload[0]["if"] == "always()" + + def test_public_package_verification_includes_core_and_mcp_live_tests(): verification = workflow("publish")["jobs"]["verify-published"] commands = "\n".join(step.get("run", "") for step in verification["steps"]) assert "scripts/check_distribution.py --published current --live" in commands assert "mcp/check_distribution.py --dist-dir published-dist --live" in commands assert verification.get("continue-on-error", "false") == "false" + + +def test_live_invocations_retry_only_transport_failures(): + core = script_namespace("scripts/check_distribution.py") + extension = script_namespace("mcp/check_distribution.py") + assert extension["LIVE_TRANSPORT_ERRORS"] == core["LIVE_TRANSPORT_ERRORS"] + assert extension["live_rerun_arguments"]() == core["live_rerun_arguments"]() + arguments = core["live_rerun_arguments"]() + assert arguments[:4] == ["--reruns", "2", "--reruns-delay", "15"] + patterns = [arguments[index + 1] for index, flag in enumerate(arguments) if flag == "--only-rerun"] + assert patterns == list(core["LIVE_TRANSPORT_ERRORS"]) + + def retried(message): + return any(re.search(pattern, message) for pattern in patterns) + + # Failures observed on the residential CI proxy leg are retried. + assert retried("Timeout: Failed to perform, curl: (28) Connection timed out after 30004 milliseconds") + assert retried("AssertionError: Connection error: Failed to perform, curl: (7) CONNECT tunnel failed, response 590") + assert retried("AuthenticationError: Failed to initialize async client: Failed to perform, curl: (28)") + assert retried("RateLimitError: Max retries exceeded due to rate limiting") + # Failures about Meta's data or the library's behaviour are not. + assert not retried("AssertionError: assert 2 == 3") + assert not retried("AssertionError: Actual Meta detail field eu_total_reach was not enriched") + assert not retried("KeyError: 'ad_archive_id'") + assert not retried("AssertionError: Meta preflight returned no ads for the broad query") diff --git a/tests/test_ci_network.py b/tests/test_ci_network.py index e06c4d4..4be0b03 100644 --- a/tests/test_ci_network.py +++ b/tests/test_ci_network.py @@ -78,3 +78,34 @@ def test_distribution_checks_do_not_filter_out_integration_regressions(): # Captured-data fault injection is labeled separately in the report, but # must still be exercised alongside every other permanent regression. assert '"not controlled"' not in inspect.getsource(main) + + +def test_scoped_proxy_matches_dns_cases_but_separates_families(monkeypatch): + from urllib.parse import unquote, urlsplit + + from tests.ci_network import scoped_ci_proxy + + monkeypatch.setenv("GITHUB_RUN_ID", "123456789") + configure_ci_network(monkeypatch, "http://groups-RESIDENTIAL,country-US:ephemeral@proxy.apify.com:8000") + shared = os.environ["METAADS_CI_PROXY"] + first = scoped_ci_proxy(shared, "authenticated_socks") + assert first == scoped_ci_proxy(shared, "authenticated_socks") + assert first != scoped_ci_proxy(shared, "independent_dns") + assert first != shared + parsed = urlsplit(first) + parameters = unquote(parsed.username).split(",") + assert "groups-RESIDENTIAL" in parameters and "country-US" in parameters + sessions = [item.removeprefix("session-") for item in parameters if item.startswith("session-")] + assert len(sessions) == 1 and len(sessions[0]) <= 50 + assert parsed.password == "ephemeral" and parsed.hostname == "proxy.apify.com" and parsed.port == 8000 + + +@pytest.mark.parametrize("proxy", [ + None, + "http://audit:ephemeral@127.0.0.1:8123", + "http://groups-RESIDENTIAL,session-userchosen:ephemeral@proxy.apify.com:8000", +]) +def test_scoped_proxy_preserves_user_selected_session_and_other_providers(proxy): + from tests.ci_network import scoped_ci_proxy + + assert scoped_ci_proxy(proxy, "authenticated_socks") == proxy diff --git a/tests/test_exports.py b/tests/test_exports.py index 529f35d..02cdc79 100644 --- a/tests/test_exports.py +++ b/tests/test_exports.py @@ -86,51 +86,14 @@ def test_csv_export_roundtrip( """ output_file = tmp_path / "test_output.csv" - # Define expected columns (matching collector.collect_to_csv) - columns = [ - "id", "page_id", "page_name", "page_url", "is_active", - "ad_status", "delivery_start_time", "delivery_stop_time", - "creative_body", "creative_title", "creative_description", - "creative_link_url", "creative_image_url", "snapshot_url", - "impressions_lower", "impressions_upper", "spend_lower", - "spend_upper", "currency", "publisher_platforms", "languages", - "funding_entity", "disclaimer", "ad_type", "collected_at", - ] - - # Write CSV + from meta_ads_collector.exports import CSV_COLUMNS, ad_to_csv_row + + columns = list(CSV_COLUMNS) with open(output_file, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=columns) writer.writeheader() for ad in collected_ads: - primary = ad.creatives[0] if ad.creatives else None - row = { - "id": ad.id, - "page_id": ad.page.id if ad.page else "", - "page_name": ad.page.name if ad.page else "", - "page_url": ad.page.page_url if ad.page else "", - "is_active": ad.is_active if ad.is_active is not None else "", - "ad_status": ad.ad_status or "", - "delivery_start_time": ad.delivery_start_time.isoformat() if ad.delivery_start_time else "", - "delivery_stop_time": ad.delivery_stop_time.isoformat() if ad.delivery_stop_time else "", - "creative_body": primary.body if primary else "", - "creative_title": primary.title if primary else "", - "creative_description": primary.description if primary else "", - "creative_link_url": primary.link_url if primary else "", - "creative_image_url": primary.image_url if primary else "", - "snapshot_url": ad.snapshot_url or ad.ad_snapshot_url or "", - "impressions_lower": ad.impressions.lower_bound if ad.impressions else "", - "impressions_upper": ad.impressions.upper_bound if ad.impressions else "", - "spend_lower": ad.spend.lower_bound if ad.spend else "", - "spend_upper": ad.spend.upper_bound if ad.spend else "", - "currency": ad.currency or "", - "publisher_platforms": ",".join(ad.publisher_platforms), - "languages": ",".join(ad.languages), - "funding_entity": ad.funding_entity or "", - "disclaimer": ad.disclaimer or "", - "ad_type": ad.ad_type or "", - "collected_at": ad.collected_at.isoformat(), - } - writer.writerow(row) + writer.writerow(ad_to_csv_row(ad)) # Read back and validate with open(output_file, encoding="utf-8") as f: diff --git a/tests/test_live_preflight.py b/tests/test_live_preflight.py index 085378b..a34b28d 100644 --- a/tests/test_live_preflight.py +++ b/tests/test_live_preflight.py @@ -8,7 +8,8 @@ @pytest.mark.integration def test_live_meta_bootstrap_search_and_field_fidelity(): - with MetaAdsClient(timeout=20, max_retries=1) as client: + # Residential CI egress can stall a single bootstrap attempt; allow a bounded retry budget. + with MetaAdsClient(timeout=30, max_retries=3) as client: client.initialize() response, _cursor = client.search_ads(query="nike", country="US", first=2) assert not response.get("error"), response.get("error") diff --git a/tests/test_live_proxy_transport.py b/tests/test_live_proxy_transport.py index 3bcad3a..838a684 100644 --- a/tests/test_live_proxy_transport.py +++ b/tests/test_live_proxy_transport.py @@ -3,6 +3,8 @@ from __future__ import annotations import ipaddress +import json +import os import secrets from urllib.parse import quote @@ -11,7 +13,31 @@ from meta_ads_collector.client import MetaAdsClient from meta_ads_collector.collector import MetaAdsCollector +from . import meta_forward_proxy from .meta_forward_proxy import MetaForwardProxy, MetaSocksProxy, _is_meta_host +from .meta_transport_diagnostics import MetaTransportDiagnostics + + +@pytest.fixture(autouse=True) +def isolated_proxy_family(request, ci_meta_network, monkeypatch): + """Keep related DNS cases matched, separate from preceding live-suite load.""" + from .ci_network import scoped_ci_proxy + + if request.node.get_closest_marker("integration"): + proxy = os.environ.get("METAADS_CI_PROXY") + if proxy: + monkeypatch.setenv("METAADS_CI_PROXY", scoped_ci_proxy(proxy, request.node.originalname)) + + +@pytest.fixture +def transport_diagnostics(record_property): + diagnostics = MetaTransportDiagnostics() + gateways = [] + yield diagnostics, gateways + destinations = [host for gateway in gateways for host in gateway.connections] + evidence = json.dumps(diagnostics.snapshot(destinations), sort_keys=True) + record_property("meta_transport", evidence) + print("Meta transport metadata: " + evidence) def _proxy_string(proxy, form): @@ -51,9 +77,54 @@ def test_forward_gateway_allows_meta_subdomains_without_allowing_lookalikes(host assert _is_meta_host(host) is allowed +def test_upstream_tunnel_retries_one_stalled_attempt_within_the_client_budget(monkeypatch): + import socket + + attempts = [] + opened = socket.socket() + try: + def flaky_upstream(host, port, upstream, server_name, timeout): + attempts.append(timeout) + if len(attempts) == 1: + raise socket.timeout("upstream stalled") + return opened + + monkeypatch.setattr(meta_forward_proxy, "_connect_upstream_once", flaky_upstream) + remote = meta_forward_proxy._connect_remote("www.facebook.com", 443, "http://user:pw@upstream.example:8080") + assert remote is opened + assert attempts == [meta_forward_proxy.UPSTREAM_ATTEMPT_TIMEOUT] * 2 + assert meta_forward_proxy.UPSTREAM_ATTEMPTS * meta_forward_proxy.UPSTREAM_ATTEMPT_TIMEOUT < 30 + assert remote.gettimeout() == meta_forward_proxy.RELAY_TIMEOUT + finally: + opened.close() + + +def test_upstream_tunnel_reports_a_persistent_stall_as_a_gateway_error(monkeypatch): + import socket + + def stalled_upstream(host, port, upstream, server_name, timeout): + raise socket.timeout("upstream stalled") + + monkeypatch.setattr(meta_forward_proxy, "_connect_upstream_once", stalled_upstream) + with pytest.raises(OSError, match="2 attempts"): + meta_forward_proxy._connect_remote("www.facebook.com", 443, "socks5h://upstream.example:1080") + + +def test_direct_tunnel_does_not_use_the_upstream_retry_path(monkeypatch): + import socket + + monkeypatch.setattr(meta_forward_proxy, "_connect_upstream_once", lambda *args: pytest.fail("no upstream")) + created = [] + monkeypatch.setattr(socket, "create_connection", lambda address, timeout: created.append((address, timeout))) + meta_forward_proxy._connect_remote("www.facebook.com", 443, None) + assert created == [(("www.facebook.com", 443), meta_forward_proxy.RELAY_TIMEOUT)] + + @pytest.mark.integration @pytest.mark.parametrize("async_mode", [False, True], ids=["sync", "async"]) -def test_live_socks5_meta_collection_survives_a_different_python_dns_view(monkeypatch, async_mode): +def test_live_socks5_meta_collection_survives_a_different_python_dns_view( + monkeypatch, async_mode, transport_diagnostics, +): import asyncio import socket @@ -68,16 +139,20 @@ def independent_dns_view(host, *args, **kwargs): monkeypatch.setattr(socket, "getaddrinfo", independent_dns_view) with MetaSocksProxy("audit@meta", "local/" + secrets.token_hex(12)) as proxy: + diagnostics, gateways = transport_diagnostics + gateways.append(proxy) address = _proxy_string(proxy, "url").replace("http://", "socks5://", 1) if async_mode: async def collect(): async with AsyncMetaAdsCollector(proxy=address, timeout=30, max_retries=2, rate_limit_delay=0.5, jitter=0) as collector: + diagnostics.instrument(monkeypatch, collector.client) return await collector.collect(query="nike", country="US", max_results=3, page_size=2) ads = asyncio.run(collect()) else: with MetaAdsCollector(proxy=address, timeout=30, max_retries=2, rate_limit_delay=0.5, jitter=0) as collector: + diagnostics.instrument(monkeypatch, collector.client) ads = list(collector.search(query="nike", country="US", max_results=3, page_size=2)) assert len(ads) == 3 assert all(ad.id and ad.page and ad.page.id for ad in ads) @@ -169,22 +244,28 @@ async def collect(): @pytest.mark.integration @pytest.mark.parametrize("scheme", ["socks5", "socks5h"]) @pytest.mark.parametrize("async_mode", [False, True], ids=["sync", "async"]) -def test_live_authenticated_socks_proxy_collects_actual_meta_ads(scheme, async_mode): +def test_live_authenticated_socks_proxy_collects_actual_meta_ads( + scheme, async_mode, monkeypatch, transport_diagnostics, +): import asyncio from meta_ads_collector.async_collector import AsyncMetaAdsCollector with MetaSocksProxy("audit@meta", "local/" + secrets.token_hex(12)) as proxy: + diagnostics, gateways = transport_diagnostics + gateways.append(proxy) address = _proxy_string(proxy, "url").replace("http://", scheme + "://", 1) if async_mode: async def collect(): async with AsyncMetaAdsCollector(proxy=address, timeout=30, max_retries=2, rate_limit_delay=0.5, jitter=0) as collector: + diagnostics.instrument(monkeypatch, collector.client) return await collector.collect(query="nike", country="US", max_results=3, page_size=2) ads = asyncio.run(collect()) else: with MetaAdsCollector(proxy=address, timeout=30, max_retries=2, rate_limit_delay=0.5, jitter=0) as collector: + diagnostics.instrument(monkeypatch, collector.client) ads = list(collector.search(query="nike", country="US", max_results=3, page_size=2)) assert len(ads) == 3 assert all(ad.id and ad.page and ad.page.id for ad in ads) diff --git a/tests/test_media_fallback.py b/tests/test_media_fallback.py new file mode 100644 index 0000000..67f1365 --- /dev/null +++ b/tests/test_media_fallback.py @@ -0,0 +1,91 @@ +"""Generic Meta CDN host fallback inside the media retry budget.""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import pytest +from curl_cffi.requests.exceptions import ConnectionError as CffiConnectionError +from curl_cffi.requests.exceptions import HTTPError as CffiHTTPError + +from meta_ads_collector.media import MediaDownloader, fallback_media_url + +REGIONAL = "https://scontent.fcai19-2.fna.fbcdn.net/v/t39.35426-6/5170_n.jpg?stp=dst-jpg_s600x600_tt6&_nc_cat=108&oh=00_abc&oe=6ADF" +GENERIC = "https://scontent.xx.fbcdn.net/v/t39.35426-6/5170_n.jpg?stp=dst-jpg_s600x600_tt6&_nc_cat=108&oh=00_abc&oe=6ADF" + + +def _ok_response(payload=b"meta-media-bytes"): + response = MagicMock() + response.status_code = 200 + response.headers = {"content-type": "image/jpeg"} + response.raise_for_status.return_value = None + response.iter_content.return_value = iter([payload]) + return response + + +@pytest.mark.parametrize("url, expected", [ + (REGIONAL, GENERIC), + ("https://scontent-dus1-1.xx.fbcdn.net/v/a.jpg?oh=1", "https://scontent.xx.fbcdn.net/v/a.jpg?oh=1"), + ("https://video.fcai19-2.fna.fbcdn.net/o1/v/t2/clip.mp4?efg=x", "https://video.xx.fbcdn.net/o1/v/t2/clip.mp4?efg=x"), + ("https://video-dus1-1.xx.fbcdn.net/o1/v/t2/clip.mp4", "https://video.xx.fbcdn.net/o1/v/t2/clip.mp4"), + (GENERIC, None), + ("https://video.xx.fbcdn.net/o1/v/t2/clip.mp4", None), + ("https://cdn.example.com/image.jpg", None), + ("https://fbcdn.net.evil.example/image.jpg", None), + ("https://scontent.fcai19-2.fna.fbcdn.net:8443/v/a.jpg", None), + ("not a url", None), +]) +def test_fallback_media_url_targets_the_generic_meta_cdn_host_only(url, expected): + assert fallback_media_url(url) == expected + + +def test_download_recovers_on_the_generic_host_after_a_regional_edge_failure(tmp_path): + session = MagicMock() + session.get.side_effect = [CffiConnectionError("CONNECT tunnel failed, response 590", code=7), _ok_response()] + downloader = MediaDownloader(tmp_path, session=session, max_retries=2) + + success, error, size = downloader._download_file(REGIONAL, tmp_path / "ad_0_image.jpg") + + assert (success, error, size) == (True, None, len(b"meta-media-bytes")) + assert [call.args[0] for call in session.get.call_args_list] == [REGIONAL, GENERIC] + assert (tmp_path / "ad_0_image.jpg").read_bytes() == b"meta-media-bytes" + + +def test_download_alternates_hosts_within_the_configured_budget(tmp_path, monkeypatch): + monkeypatch.setattr("meta_ads_collector.media.time.sleep", lambda _seconds: None) + session = MagicMock() + session.get.side_effect = CffiConnectionError("CONNECT tunnel failed, response 590", code=7) + downloader = MediaDownloader(tmp_path, session=session, max_retries=3) + + success, error, size = downloader._download_file(REGIONAL, tmp_path / "ad_0_image.jpg") + + assert success is False and size is None + assert "590" in error + assert [call.args[0] for call in session.get.call_args_list] == [REGIONAL, GENERIC, REGIONAL] + assert not list(tmp_path.iterdir()) + + +def test_download_keeps_the_original_host_for_non_meta_urls(tmp_path, monkeypatch): + monkeypatch.setattr("meta_ads_collector.media.time.sleep", lambda _seconds: None) + session = MagicMock() + session.get.side_effect = [CffiConnectionError("reset", code=56), _ok_response()] + downloader = MediaDownloader(tmp_path, session=session, max_retries=2) + url = "https://cdn.example.com/image.jpg" + + assert downloader._download_file(url, tmp_path / "ad_0_image.jpg")[0] is True + assert [call.args[0] for call in session.get.call_args_list] == [url, url] + + +def test_expired_url_does_not_retry_on_the_generic_host(tmp_path): + response = MagicMock(status_code=403) + error = CffiHTTPError("403 Forbidden") + error.response = response + response.raise_for_status.side_effect = error + session = MagicMock() + session.get.return_value = response + downloader = MediaDownloader(tmp_path, session=session, max_retries=3) + + success, message, _size = downloader._download_file(REGIONAL, tmp_path / "ad_0_image.jpg") + + assert success is False and "403" in message + assert session.get.call_count == 1 diff --git a/tests/test_meta_transport_diagnostics.py b/tests/test_meta_transport_diagnostics.py new file mode 100644 index 0000000..192d634 --- /dev/null +++ b/tests/test_meta_transport_diagnostics.py @@ -0,0 +1,56 @@ +"""Privacy and transparency contracts for metadata, separate from live collection.""" + +import json +from types import SimpleNamespace + +import pytest + +from tests.meta_transport_diagnostics import MetaTransportDiagnostics, response_metadata + + +@pytest.mark.parametrize("prefix", ["", "for (;;);"]) +def test_response_metadata_never_serializes_tokens_cookies_messages_or_url_query(prefix): + sensitive = "ephemeral-private-canary" + client = SimpleNamespace(_tokens={"lsd": sensitive}) + # Exercise the observed Meta GraphQL error shape with a deliberate canary + # in fields that must never enter public evidence. This is a privacy unit + # contract, not a substitute for the actual Meta SOCKS integration cases. + body = {"errors": [{"code": 1675004, "message": sensitive}, {"code": sensitive}], "token": sensitive} + response = SimpleNamespace(status_code=200, text=prefix + json.dumps(body), cookies={"datr": sensitive}) + evidence = response_metadata(client, "POST", "https://www.facebook.com/api/graphql/?token=" + sensitive, response) + assert evidence == { + "method": "POST", "endpoint": "graphql", "host": "www.facebook.com", + "status": 200, "error_codes": [1675004], "lsd_present": True, + } + assert sensitive not in json.dumps(evidence) + + +@pytest.mark.parametrize("body", ["not JSON", "[]", "null", '{"errors": true}']) +def test_unstructured_response_does_not_leak_body_or_break_the_observer(body): + evidence = response_metadata(SimpleNamespace(_tokens={}), "POST", "https://www.facebook.com/api/graphql/", + SimpleNamespace(status_code=403, text=body)) + assert evidence["status"] == 403 and evidence["error_codes"] == [] and not evidence["lsd_present"] + + +@pytest.mark.parametrize("async_mode", [False, True]) +def test_instrumentation_preserves_response_identity_and_request_arguments(monkeypatch, async_mode): + import asyncio + + response = SimpleNamespace(status_code=200, text="") + arguments = [] + + def request(method, url, **kwargs): + arguments.append((method, url, kwargs)) + return response + + async def async_request(method, url, **kwargs): + return request(method, url, **kwargs) + + client = SimpleNamespace(_make_request=async_request if async_mode else request, _tokens={}) + diagnostics = MetaTransportDiagnostics() + diagnostics.instrument(monkeypatch, client) + call = client._make_request("GET", "https://www.facebook.com/", headers={"accept": "text/html"}) + result = asyncio.run(call) if async_mode else call + assert result is response + assert arguments == [("GET", "https://www.facebook.com/", {"headers": {"accept": "text/html"}})] + assert diagnostics.snapshot(["www.facebook.com"])["responses"][0]["status"] == 200